2012-03-30 115 views
1

我想讓我的腳本接受可變參數。我如何單獨檢查它們?shell腳本的變量參數

例如

./myscript arg1 arg2 arg3 arg4 

or 

./myscript arg4 arg2 arg3 

的參數可以是任何數量和任何順序。我想檢查是否存在arg4字符串,而不管參數號碼。

我該怎麼做?

感謝,

+0

這些參數是否固定了字符串(類似'--help','--version'等)還是它們是「什麼」? – sarnold 2012-03-30 23:43:09

+0

Duplicate,http://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-bash-script,http://stackoverflow.com/questions/4528292/passing-multiple-arguments-to -a-unix-shell-script – moodywoody 2012-03-30 23:45:45

+0

是的。我通過幾個標誌作爲腳本的參數不一定是固定的數字。 – Kitcha 2012-03-30 23:46:06

回答

3

最安全的方式—,處理在參數空白的一切可能性的方式,等等—是寫一個明確的循環:

arg4_is_an_argument='' 
for arg in "[email protected]" ; do 
    if [[ "$arg" = 'arg4' ]] ; then 
     arg4_is_an_argument=1 
    fi 
done 
if [[ "$arg4_is_an_argument" ]] ; then 
    : the argument was present 
else 
    : the argument was not present 
fi 

如果您確定您的論點將不包含空格—或至少,如果你不特別擔心那種情況下—那麼你可以縮短到:

if [[ " $* " == *' arg4 '* ]] ; fi 
    : the argument was almost certainly present 
else 
    : the argument was not present 
fi 
0

也許這可以幫助。

#!/bin/bash 
# this is myscript.sh 

[ `echo $* | grep arg4` ] && echo true || echo false 
0

這是玩弄與命令行「參數」的典型詮釋,但我開始了我的大部分的bash腳本與以下,作爲一種簡單的方式來增加--help支持:

if [[ "[email protected]" =~ --help ]]; then 
    echo 'So, lemme tell you how to work this here script...' 
    exit 
fi 

主要缺點是,這也會由像request--help.log,--no--help等參數(不只是--help,這可能是您的解決方案的要求)引發。

要在您的案件,不適用這種方法,你會寫是這樣的:

[[ "[email protected]" =~ arg4 ]] && echo "Ahoy, arg4 sighted!" 

獎金!如果你的腳本至少需要一個命令行參數,你同樣可以觸發時沒有提供參數的幫助消息:

if [[ "${@---help}" =~ --help ]]; then 
    echo 'Ok first yer gonna need to find a file...' 
    exit 1 
fi 

它使用空值變量替換語法${VAR-default}產生幻覺一--help說法,如果絕對沒有提出了論據。