在命令行上解析shell脚本的输入

时间:2013-06-13 22:36:08

标签: bash shell unix loops scripting

我正在尝试将字符串后的所有其他内容分配给$ @,但也会选择橙色。我认为这个转变将作为其余的args,但输出也是橙色。

$ cat try.sh
#!/usr/bin/bash

str1="$1"
str2="$2"; shift

echo "$str1"
echo "$str2"

for i in "$@"
do
echo "rest are $i"
done

./try.sh apple orange 3 4 5
apple
orange
rest are orange
rest are 3
rest are 4
rest are 5

1 个答案:

答案 0 :(得分:3)

你需要做两次转移以摆脱苹果和橙色。单个班次只会偏离一个参数,无论代码在哪里 - 它与上次访问/分配的参数无关。

 str1="$1"
 str2="$2"; shift ; shift

 str1="$1"; shift
 str2="$1"; shift # Notice that due to prior shift, orange now is in $1, not $2
相关问题