我敢肯定,当您进入 shell 编程时,这是一件很容易的事。不幸的是,我不是,而且我过得很艰难......
我需要验证传递给 shell 脚本的参数。我还想存储在数组中传递的所有参数,因为稍后我需要进一步分离。
我有一个参数“-o”,后面必须跟 0 或 1。因此,我想检查以下参数是否有效。这是我尝试过的:
# Loop over all arguments
for i in "$@"
do
# Check if there is a "-" as first character,
# if so: it's a parameter
str="$i"
minus=${str:0:1}
# Special case: -o is followed by 0 or 1
# this parameter needs to be added, too
if [ "$str" == "-o" ]
then
newIdx=`echo $((i+1))` # <-- problem here: how can I access the script param by a generated index?
par="$($newIdx)"
if [[ "$par" != "0" || "$par" != "1" ]]
then
echo "script error: The -o parameter needs to be followed by 0 or 1"
exit -1
fi
paramIndex=$((paramIndex+1))
elif [ "$minus" == "-" ]
then
myArray[$paramIndex]="$i"
paramIndex=$((paramIndex+1))
fi
done
我尝试了各种方法,但没有成功……如果有人能阐明这一点,我将不胜感激!
谢谢