100

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?

4

3 回答 3

148

case语句使用 glob,而不是正则表达式,并坚持完全匹配。

所以空字符串像往常一样写成""or ''

case "$command" in
  "")        do_empty ;;
  something) do_something ;;
  prefix*)   do_prefix ;;
  *)         do_other ;;
esac
于 2013-07-10T16:10:33.653 回答
5

我使用一个简单的跌倒。第二个 case 语句不会捕获任何传递的参数 ($1=""),但后面的 * 将捕获任何未知参数。翻转 "") 和 *) 将不起作用,因为 *) 在这种情况下每次都会捕获所有内容,甚至是空白。

#!/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
于 2014-04-05T00:22:01.820 回答
1

这是我的做法(对他们自己):

#!/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

如果我正在搜索一个存在于包含数十个 cgi 文件的文件系统中的一个或两个文件中的子例程,我输入搜索词,例如“ssn_format”。bash 在一个文本文件 (finder.txt) 中将结果返回给我,如下所示:

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

于 2017-01-23T16:03:23.460 回答