gui*_*low 1 parameters bash shell scripting
当你进入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
Run Code Online (Sandbox Code Playgroud)
我尝试了各种各样的东西,但它没有用......如果有人能够阐明这一点,我将不胜感激!
谢谢
在bash,您可以使用间接参数扩展来访问任意位置参数.
$ set a b c
$ paramIndex=2
$ echo $2
b
$ echo ${!paramIndex}
b
Run Code Online (Sandbox Code Playgroud)