Bash case 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16673570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:45:05  来源:igfitidea点击:

Bash case statement

bashshellcase

提问by bsmoo

I'm trying to learn case as I was to write a fully functional script.

我正在尝试学习案例,因为我要编写一个功能齐全的脚本。

I'm starting off with the below

我从下面开始

#!/bin/sh
case $@ in

    -h|--help)
            echo "You have selected Help"
            ;;
    -B|-b)
            echo "You have selected B"
            ;;
    -C|-c)
            echo "You have selected C"
            ;;
      *)
            echo "Valid Choices are A,B,C"
            exit 1
            ;;
esac

I want to use two of these options:

我想使用其中两个选项:

./getopts.sh -h -c

But i get this result Valid Choices are A,B,C

但我得到了这个结果有效的选择是 A、B、C

Please can you help out and let me know what I'm doing wrong?

请你能帮忙告诉我我做错了什么吗?

I want to build a script that will do something if you enter one option but do multiple things if you enter multiple.

我想构建一个脚本,如果您输入一个选项,该脚本将执行某些操作,但如果您输入多个选项,则该脚本将执行多项操作。

Also how would i parse $1 to this script as surley which ever option i enter first (-h) will be $1 ??

另外我将如何将 $1 解析为这个脚本作为 surley 我首先输入的选项(-h)将是 $1 ?

Thanks!

谢谢!

回答by Bruce Barnett

Try this

尝试这个

#!/bin/sh

usage() {
    echo `basename 
for arg in "$@"; do
    case $arg in
       ....
    esac
done
`: ERROR: $* 1>&2 echo usage: `basename ##代码##` '[-a] [-b] [-c] [file ...]' 1>&2 exit 1 } while : do case "" in -a|-A) echo you picked A;; -b|-B) echo you picked B;; -c|-C) echo you picked C;; -*) usage "bad argument ";; *) break;; esac shift done

回答by chepner

Using getoptor getoptsis the better solution. But to answer your immediate question, $@is allof your arguments, so -h -c, which doesn't match any of the single-argument patterns in your case statement. You would still need to iterate over your arguments like so

使用getoptorgetopts是更好的解决方案。但是要回答您的直接问题,$@是您的所有参数,所以-h -c,与您的 case 语句中的任何单参数模式都不匹配。你仍然需要像这样迭代你的论点

##代码##

回答by nitin

to parse the positional arguments like ... $1 , just use $1 in the case stmt and then at the end ... use shift to pust the 2nd arg to $1 and likewise .

要解析像... $1 这样的位置参数,只需在案例 stmt 中使用 $1 ,然后在最后...使用 shift 将第二个 arg 推到 $1 ,同样如此。

also i would put the case stmt in a while loop or better a fxn so that i can run it twice for the two options or the number of options ..........

此外,我会将案例 stmt 放入 while 循环或更好的 fxn 中,以便我可以针对两个选项或选项数量运行它两次.......

$# will let you know how many options/arguments were there .

$# 会让你知道有多少选项/参数。