Bash case statement

二次信任 提交于 2019-12-12 07:14:39

问题


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

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 ??

Thanks!


回答1:


Try this

#!/bin/sh

usage() {
    echo `basename $0`: ERROR: $* 1>&2
    echo usage: `basename $0` '[-a] [-b] [-c] 
        [file ...]' 1>&2
    exit 1
}


while :
do
    case "$1" in
    -a|-A) echo you picked A;;
    -b|-B) echo you picked B;;
    -c|-C) echo you picked C;;
    -*) usage "bad argument $1";;
    *) break;;
    esac
    shift
done



回答2:


Using getopt or getopts is the better solution. But to answer your immediate question, $@ is all of 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

for arg in "$@"; do
    case $arg in
       ....
    esac
done



回答3:


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 .

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 ..........

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



来源:https://stackoverflow.com/questions/16673570/bash-case-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!