如何将参数转发给 bash 脚本中的其他命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1537673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I forward parameters to other command in bash script?
提问by ?ukasz Lew
Inside my bash script, I would like to parse zero, one or two parameters (the script can recognize them), then forward the remaining parameters to a command invoked in the script. How can I do that?
在我的 bash 脚本中,我想解析零、一个或两个参数(脚本可以识别它们),然后将剩余的参数转发给脚本中调用的命令。我怎样才能做到这一点?
回答by unwind
Use the shift
built-in command to "eat" the arguments. Then call the child process and pass it the "$@"
argument to include all remaining arguments. Notice the quotes, they should be kept, since they cause the expansion of the argument list to be properly quoted.
使用shift
内置命令来“吃掉”参数。然后调用子进程并将"$@"
参数传递给它以包含所有剩余的参数。注意引号,应该保留它们,因为它们会导致参数列表的扩展被正确引用。
回答by Steve B.
bash uses the shiftcommand:
bash 使用shift命令:
e.g. shifttest.sh:
例如 shifttest.sh:
#!/bin/bash
echo
shift
echo
shifttest.sh 1 2 3 produces
shifttest.sh 1 2 3 产生
1
2 3
回答by Robert Lujo
Bash supports subsetting parameters (see Subsets and substrings), so you can choose which parameters to process/pass like this.
Bash 支持子集参数(请参阅子集和子字符串),因此您可以像这样选择要处理/传递的参数。
open new file and edit it: vim
r.sh
:echo "params only 2 : ${@:2:1}" echo "params 2 and 3 : ${@:2:2}" echo "params all from 2: ${@:2:99}" echo "params all from 2: ${@:2}"
run it:
$ chmod u+x r.sh $ ./r.sh 1 2 3 4 5 6 7 8 9 10
the result is:
params only 2 : 2 params 2 and 3 : 2 3 params all from 2: 2 3 4 5 6 7 8 9 10 params all from 2: 2 3 4 5 6 7 8 9 10
打开新文件并编辑它: vim
r.sh
:echo "params only 2 : ${@:2:1}" echo "params 2 and 3 : ${@:2:2}" echo "params all from 2: ${@:2:99}" echo "params all from 2: ${@:2}"
运行:
$ chmod u+x r.sh $ ./r.sh 1 2 3 4 5 6 7 8 9 10
结果是:
params only 2 : 2 params 2 and 3 : 2 3 params all from 2: 2 3 4 5 6 7 8 9 10 params all from 2: 2 3 4 5 6 7 8 9 10