【发布时间】:2013-06-04 11:08:45
【问题描述】:
我敢肯定,当您从事 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
我尝试了各种方法,但都没有成功... 如果有人能阐明这一点,将不胜感激!
谢谢
【问题讨论】:
-
使用
while-loop 和shift可能会更容易
标签: bash shell parameters scripting