How do I test for an empty string in a Bash case statement?

Singlestone picture Singlestone · Jul 10, 2013 · Viewed 38.5k times · Source

I have a Bash script that performs actions based on the value of a variable. The general syntax of the case statement is:

case ${command} in
   start)  do_start ;;
   stop)   do_stop ;;
   config) do_config ;;
   *)      do_help ;;
esac

I'd like to execute a default routine if no command is provided, and do_help if the command is unrecognized. I tried omitting the case value thus:

case ${command} in
   )       do_default ;;
   ...
   *)      do_help ;;
esac

The result was predictable, I suppose:

syntax error near unexpected token `)'

Then I tried using a regex:

case ${command} in
   ^$)     do_default ;;
   ...
   *)      do_help ;;
esac

With this, an empty ${command} falls through to the * case.

Am I trying to do the impossible?

Answer

rici picture rici · Jul 10, 2013

The case statement uses globs, not regexes, and insists on exact matches.

So the empty string is written, as usual, as "" or '':

case "$command" in
  "")        do_empty ;;
  something) do_something ;;
  prefix*)   do_prefix ;;
  *)         do_other ;;
esac