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

标签 bash shell unix loops scripting

我试图将字符串后的所有其他内容分配给 $@,但也选择了橙色。我认为转变将作为其余参数,但输出也选择橙色。

$ 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/

相关文章:

Linux Bash 无限循环与 sleep

c++ - 使用格式化结果解析搜索/替换头文件

bash - 在 bash 中重用变量

shell - 如何在 KornShell (ksh) 中正确保存 IFS

c++ - 函数的多重声明 make 命令 UNIX

linux - 如果输出字段之一为空,awk 如何打印 "NA"

node.js - 使用 --experimental-specifier-resolution=node 时如何让 yargs 自动完成工作

perl - 如何在bat文件中指定Cygwin模式下需要调用的脚本?

编译的C文件不可执行

linux - 带有命令行 grep 和拆分定界符的 ubuntu linux shell 脚本