通过索引访问Shell脚本参数 [英] Accessing shell script arguments by index
问题描述
当您进入shell编程时,我确定这是不费吹灰之力的. 不幸的是我不是,我现在很难过...
I'm sure this is a no-brainer when you're into shell programming. Unfortunately I'm not and I'm having a pretty hard time ...
我需要验证传递给shell脚本的参数. 我还想将所有传递的参数存储在数组中,因为以后需要进一步分离.
I need to verify arguments passed to a shell script. I also want to store all parameters passed in an array as I need further separation later.
我有一个参数"-o",其后必须为0或1. 因此,我想检查以下参数是否有效. 这是我尝试过的:
I have an argument "-o" which must be followed by either 0 or 1. Thus, I want to check if the following argument is valid. Here's what I tried:
# 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
我尝试了各种方法,但是没有用... 如果有人可以阐明这一点,将不胜感激!
I tried various things but it didn't work ... Would be grateful if someone could shed light on this!
谢谢
推荐答案
在bash
中,可以使用间接参数扩展来访问任意位置参数.
In bash
, you can use indirect parameter expansion to access an arbitrary positional parameter.
$ set a b c
$ paramIndex=2
$ echo $2
b
$ echo ${!paramIndex}
b
这篇关于通过索引访问Shell脚本参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!