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

StringBashNullCase

String Problem Overview


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?

String Solutions


Solution 1 - String

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

Solution 2 - String

I use a simple fall through. no parameters passed ($1="") will be caught by the second case statement, yet the following * will catch any unknown parameter. Flipping the "") and *) will not work as *) will catch everything every time in that case, even blanks.

#!/usr/local/bin/bash
# testcase.sh
case "$1" in
  abc)
    echo "this $1 word was seen."
    ;;
  "") 
    echo "no $1 word at all was seen."
    ;;
  *)
    echo "any $1 word was seen."
    ;;
esac

Solution 3 - String

Here's how I do it (to each their own):

#!/bin/sh

echo -en "Enter string: "
read string
> finder.txt
echo "--" >> finder.txt

for file in `find . -name '*cgi'`

do

x=`grep -i -e "$string" $file`

case $x in
"" )
     echo "Skipping $file";
;;
*)
     echo "$file: " >> finder.txt
     echo "$x" >> finder.txt
     echo "--" >> finder.txt
;;
esac

done

more finder.txt

If I am searching for a subroutine that exists in one or two files in a filesystem containing dozens of cgi files I enter the search term, e.g. 'ssn_format'. bash gives me back the results in a text file (finder.txt) that looks like this:

-- ./registry/master_person_index.cgi: SQLClinic::Security::ssn_format($user,$script_name,$local,$Local,$ssn) if $ssn ne "";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSinglestoneView Question on Stackoverflow
Solution 1 - StringriciView Answer on Stackoverflow
Solution 2 - StringErnieView Answer on Stackoverflow
Solution 3 - StringThomas Altfather GoodView Answer on Stackoverflow