2017-10-13 116 views
0

的下面while循环我的一个壳中存在称作test.shUNIX - getopts的多个开关

我想运行下面的命令

ksh的-x test.sh -c -e文件1文件2

我想while循环的循环中执行这两个C)情况下,第一则E)的情况下,但目前它只是在执行C)的情况下

有人能告诉我如何得到它来执行都?第一批C类),那么E)

while getopts ":c:e:" opt; do 
    case $opt in 
     c) 
      gzip -9 archivedfile 
      ;; 
     e) 
      ksh test2.sh archivedfile 
      ;; 
    esac 
    shift 
done 

回答

0

使用;&

case c in 
     c) 
      echo got c 
      ;& 
     c|e) 
      echo got c or e 
      ;; 
esac 

看到基于您的示例脚本调用man ksh

If ;& is used in place of ;; the next subsequent list, if any, is executed.

+0

我试过,但我得到一个错误: – DaveMac001

+0

语法错误在行xx:'&'意想不到 – DaveMac001

+0

张贴块的作品。其他版本? 'ksh --version' is'sh(AT&T Research)93u + 2012-08-01'('ksh93') – toting

2

ksh -x test.sh -c -e file1 file2 
  • 的“-c”选项确实有一个说法
  • 的“-e”选项有一个参数(即“文件1”)

如果是这种情况,请尝试在getopts选项字符串去掉字母“C”后的冒号(:),例如:

while getopts ":ce:" opt; do 

如果这能解决您的问题...请继续阅读了解更多详情...


当冒号(:)跟随在getopts选项字符串的信,这表示该选项有一个参数,这反过来又意味着OPTARG将被设置为从所述命令行读取下一个项目。

如果getopts选项字符串中的字母后没有冒号,则表示该选项没有参数,这意味着OPTARG将被取消设置。


我们可以看到此行为与下面的示例脚本:

对于我们期待我们的每一个选项(C,E)后的参数这第一个脚本 - 后注意冒号(:)在getopts选项字符串每个字母(C,E):

$ cat test1.sh 
#!/bin/ksh 

while getopts :c:e: opt 
do 
     case $opt in 
       c)  echo "c: OPTARG='${OPTARG:-undefined}'" ;; 
       e)  echo "e: OPTARG='${OPTARG:-undefined}'" ;; 
       *)  echo "invalid flag" ;; 
     esac 
done 

几个试验运行:

$ test1.sh -c -e file1 
c: OPTARG='-e' 
  • 因为我们的'c'选项/标志后跟一个冒号(c :),'-e'被视为'-c'选项的参数;因为“-e”在这个穿过getopts消耗...
  • 没有更多的选项标志来处理,因此getopts情况下为“E”选项是从来没有访问
$ test1.sh -c filex -e file1 
c: OPTARG='filex' 
e: OPTARG='file1'
  • 因为我们提供了一个参数为我们的选项/标志(C,E),我们认为这是期望

现在两个getopts箱子进行处理,如果我们不希望“-c '选项有一个参数,那么我们需要删除冒号(:)后面的字母“C”在我们getopts选项字符串:

$ cat test2.sh 
#!/bin/ksh 

while getopts :ce: opt 
do 
     case $opt in 
       c)  echo "c: OPTARG='${OPTARG:-undefined}'" ;; 
       e)  echo "e: OPTARG='${OPTARG:-undefined}'" ;; 
       *)  echo "invalid flag" ;; 
     esac 
done 

$ test2.sh -c -e file1 
c: OPTARG='undefined' 
e: OPTARG='file1' 
  • ,因为我们的“C”选项/标志跟一个冒号,getopts不为下一次通过getopts的“-e”选项/标志处理并OPTARG被设置为“文件1”
从命令行,这意味着读取的任何更多的项目...