PFKrang
PFKrang

Reputation: 289

bash script case statement needs to detect specific arguments

I have to write this script where it will display each entry that is entered in on its own line and separate each line with "*****". I've already got that down for the most part but now I need it to detect when the word "TestError" and/or "now" is entered in as an argument. The way it is setup right now it will detect those words correctly if they are the first argument on the line, I'm just not sure how to set it up where it will detect the word regardless of which argument it is on the line. Also I need help with the *? case where I need it to say "Do not know what to do with " for every other argument that is not "TestError" or "now", at the moment it will do it for the first argument but not the rest.

Would it work the way it is right now? Or would I have to use only the *? and * cases and just put an if/then/else/fi statement in the *? case in order to find the "TestError" "now" and any other argument.

# template.sh
function usage
{
  echo "usage: $0 arguments ..."
  if [ $# -eq 1 ]
  then echo "ERROR: $1"
  fi
}



   # Script starts after this line.


case $1 in

  TestError)
     usage $*
     ;;
  now)
     time=$(date +%X)
     echo "It is now $time"
     ;;
  *?)
     echo "My Name"
     date
     echo
     usage
     printf "%s\n*****\n" "Do not know what to do with " "$@"
     ;;
  *)
     usage
     ;;
esac

Upvotes: 0

Views: 190

Answers (1)

chepner
chepner

Reputation: 531075

You'll need to loop over the arguments, executing the case statement for each one.

for arg in "$@"; do
    case $arg in

      TestError)
        usage $*
        ;;
      now)
        time=$(date +%X)
        echo "It is now $time"
        ;;
      *?)
        echo "My Name"
        date
        echo
        usage
        printf "%s\n*****\n" "Do not know what to do with " "$@"
        ;;
      *)
        usage
        ;;
    esac
done

* and *? will match the same strings. Did you mean to match the ? literally (*\?)?

Upvotes: 2

Related Questions