下面是我的代碼當我在Bash函數中使用getopts時,爲什麼它在第二次調用時忽略參數?
function waitTillGWState
{
if [[ $# -lt 6 ]] ; then
echo "$FUNCNAME:: Wrong parameter specified. Exiting."
exit 1
fi
local Fname1
local fset
local state
local lhost
echo "$# [email protected]"
waitTillGWState_Usage() { echo "waitTillGWState: [-F <Fname1> -t <Fname2> -S <state> -h <host>]" 1>&2; exit; }
while getopts F:t:S:h: x; do
case ${x} in
F)
Fname1="${OPTARG}"
echo "Value of Fname1 is $Fname1"
;;
t)
Fname2="${OPTARG}"
echo "Value of Fname2 is $Fname2"
;;
S)
state="${OPTARG}"
echo "Value of state is $state"
;;
h)
lhost="${OPTARG}"
echo "Value of lhost is $lhost"
;;
*)
waitTillGWState_Usage
;;
esac
done
shift $((OPTIND-1))
echo "Values are $Fname1 $Fname2 $state $lhost"
if [[ -z "${lhost}" ]] ; then
lhost=`hostname`
fi
echo "Values are $Fname1 $Fname2 $state $lhost"
return 0
}
waitTillGWState -F Fname1 -t X4 -S Active
waitTillGWState -F Fname1 -t X4 -S Disconnectecd
現在,當我運行這個,這個完美的作品第一次。但第二次失去了價值。
+ waitTillGWState -F Fname1 -t X4 -S Active
+ [[ 6 -lt 6 ]]
+ local Fname1
+ local fset
+ local state
+ local lhost
+ echo '6 -F' Fname1 -t X4 -S Active
6 -F Fname1 -t X4 -S Active
+ getopts F:t:S:h: x
+ case ${x} in
+ Fname1=Fname1
+ echo 'Value of Fname1 is Fname1'
Value of Fname1 is Fname1
+ getopts F:t:S:h: x
+ case ${x} in
+ Fname2=X4
+ echo 'Value of Fname2 is X4'
Value of Fname2 is X4
+ getopts F:t:S:h: x
+ case ${x} in
+ state=Active
+ echo 'Value of state is Active'
Value of state is Active
+ getopts F:t:S:h: x
+ shift 6
+ echo 'Values are Fname1 X4 Active '
Values are Fname1 X4 Active
+ [[ -z '' ]]
++ hostname
+ lhost=p7fbn11
+ echo 'Values are Fname1 X4 Active p7fbn11'
Values are Fname1 X4 Active p7fbn11
+ return 0
+ waitTillGWState -F Fname1 -t X4 -S Disconnectecd
+ [[ 6 -lt 6 ]]
+ local Fname1
+ local fset
+ local state
+ local lhost
+ echo '6 -F' Fname1 -t X4 -S Disconnectecd
6 -F Fname1 -t X4 -S Disconnectecd
+ getopts F:t:S:h: x
+ shift 6
+ echo 'Values are X4 '
Values are X4
+ [[ -z '' ]]
++ hostname
+ lhost=myhost1
+ echo 'Values are X4 myhost1'
Values are X4 myhost1
+ return 0
因此,我在第二次調用時失去了數值。
任何人都知道爲什麼會發生這種情況?
我試過也沒有局部變量。
可選參數是顧名思義可選的參數。有時候需要一個可選的參數是誘人的,但這樣做通常是一個壞主意,而不僅僅是因爲它違反了參數處理的準則。即使你決定要求可選參數,只要檢查參數計數並不是一個很好的方法。如果用戶調用'waitTillGWState -F file1 -F file2 -F file3'會怎麼樣? – rici
我同意。這是照顧。感謝提醒。 –