2011-10-07 33 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

它允許您從位置參數中刪除剛纔處理的選項,以便您可以從命令行訪問任何其他參數。 –