Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 558
Singlestone Avatar asked Jul 10 '13 15:07

Singlestone


People also ask

How do you check if a string starts with a letter in bash?

We can use the double equals ( == ) comparison operator in bash, to check if a string starts with another substring. In the above code, if a $name variable starts with ru then the output is “true” otherwise it returns “false”.


1 Answers

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 
like image 178
rici Avatar answered Sep 26 '22 00:09

rici