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?
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”.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With