How do I test for an empty string in a Bash case statement?
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
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
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 "";