我试图将字符串后的所有其他内容分配给 $@,但也选择了橙色。我认为转变将作为其余参数,但输出也选择橙色。
$ 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
最佳答案
你需要轮类两次才能去掉苹果和橙子。一次移位只会关闭一个参数,无论它在代码中的哪个位置 - 它与上次访问/分配的参数无关。
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
关于bash - 在命令行上解析 shell 脚本的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098347/