2

我正在尝试将字符串之后的所有其他内容分配给 $@ 但也选择了橙色。我认为这种转变将与其余的 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
4

1 回答 1

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
于 2013-06-13T22:39:13.620 回答