【问题标题】:parsing inputs to shell script on command line在命令行上解析输入到 shell 脚本
【发布时间】:2013-06-10 12:06:18
【问题描述】:

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

【问题讨论】:

  • 在 bash 会话中键入 help shift

标签: bash shell unix loops scripting


【解决方案1】:

您需要换两次才能摆脱苹果和橙子。单次移位只会关闭 一个 参数,无论它在代码中的哪个位置 - 它与上次访问/分配的参数无关。

 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

【讨论】:

  • 或者使用shift 2——指定要移位的数字通常用于使用getopts的脚本中:解析选项后,您将使用shift $((OPTIND-1))