2011-10-07 31 views
1

如何获得使用getopts的在bash脚本的使用

./myscript --p 1984 --n someName

#!/bin/bash 

while getopts :npr opt 
do 
    case $opt in 
    n) echo name= ???    ;; 
    p) echo port= ???    ;; 
    r) echo robot= "Something"  ;; 
    ?) echo "Useage: -p [#]"  ;; 
    esac 
done 

如何我访问以下命令选项参数的命令后,agrument?

此外,如果我输入:./myscript --p 1985我想知道怎么回声1985回来,并与该论点工作。

+1

当然,你实际上调用命令'的MyScript -p 1984年-n someName' –

回答

3

在bash中,请参阅help getopts:“当选项需要参数时,getopts将该参数放入shell变量OPTARG。”

usage() { echo "Usage: $(basename $0) -n name -p port -r"; exit; } 

while getopts :n:p:r opt # don't forget the colons for opts that take an arg 
do 
    case $opt in 
    n) name="$OPTARG" ;; 
    p) port="$OPTARG" ;; 
    r) robot=chicken ;; 
    ?) usage ;; 
    esac 
done 
shift $((OPTIND - 1)) 

echo "the name is $name" 
echo "the port is $port" 

我敢肯定,你可以围绕谷歌的解决方案来解析在bash选项。这里有一个几分钟的努力:

#!/bin/bash 

usage() { echo foo; exit; } 

while [[ $1 == -* ]]; do 
    case "$1" in 
    --) shift 1; break ;; 
    -p|--p|--port) port="$2"; shift 2;; 
    -n|--n|--name) name="$2"; shift 2;; 
    *) echo "unknown option: $1"; usage;; 
    esac 
done 

echo "the name is $name" 
echo "the port is $port" 
echo "the rest of the args are:"; (IFS=,; echo "$*") 

和测试,

$ bash longopts.sh --port 1234 --bar a b c 
unknown option: --bar 
foo 
$ bash longopts.sh --port 1234 a b c 
the name is 
the port is 1234 
the rest of the args are: 
a,b,c 
+0

是的,我抄这个准确,仍然不能得到它的工作 – stackoverflow

+0

转变$((OPTIND - 1))做什么? – stackoverflow

+1

它允许您从位置参数中删除刚才处理的选项,以便您可以从命令行访问任何其他参数。 –