2011-10-04 79 views
3

什么是最简单,最直接的使用方法getopts in bash脚本。你如何使用getopts?

,如果我有一个名为脚本:的MyScriptCAN取的参数:-p -r -s -x

if argument x then exit 
if argument p then echo "port 10" 
if argument s then add 2+2 
if argument r then echo env 

这是一个假设的脚本,但我只想喜欢看这样做的例子。 [在bash shell脚本使用getopts的获得长期和短期的命令行选项]的

+0

可能重复(http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell -script-to-get-long-and-short-command-line-options) – 2011-10-04 13:46:43

+0

我看过它,没有帮助我。谢谢你指出,虽然 – stackoverflow

回答

9
while getopts :xpsr opt; do 
    case $opt in 
    x) exit        ;; 
    p) echo port 10      ;; 
    s) ((2 + 2))       ;; 
    r) echo env       ;; 
    \?) echo "${0##*/}" [ -xpsr ]; exit 1 ;; 
    esac 
done 
+0

甜..感谢Dimitre。但是这最后一部分是做什么的? \? )echo“$ {0 ## * /}”[-xpsr];退出1 – stackoverflow

+1

打印使用情况并在传递无效选项时存在。 –

+0

你不会展示如何处理其余的论点...... –

3
usage() 
{ 
    echo "Usage: $0 [-o <offset>] [-h];" 
    exit 0; 
} 

# -o (offset) need a value 
# -h prints help 
offset=0 # 0 is default offset 

while getopts o:s opt 
do 
    case "$opt" in 
    d) offset="$OPTARG";; # changing offset 
    s) usage    # calls function "usage" 
    \?) echo "$OPTARG is an unknown option" 
     exit 1;; # all other options 
    esac 
done 

shift $((OPTIND-1)) 
+1

在哪个shell中转换$ OPTIND-1表达式工作?它通常必须是'$(($ OPTIND - 1))',不是。 –

+1

甚至:'$((OPTIND - 1))',这是现在的标准。 –

+0

我修好了,对不起 –