如何在 Bash case 语句中测试空字符串?

我有一个 Bash 脚本,它根据变量的值执行操作。Case 语句的一般语法是:

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

如果没有提供命令,我想执行一个默认例程,如果命令无法识别,则执行 do_help。我试图省略案例价值:

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

我想,结果是可以预见的:

syntax error near unexpected token `)'

然后我尝试使用 regex:

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

这样,一个空的 ${command}就落到了 *的情况下。

我是在做不可能的事吗?

52190 次浏览

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 "";