如何将参数转发给 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:35:27  来源:igfitidea点击:

How do I forward parameters to other command in bash script?

bashcommand-line

提问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 shiftbuilt-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 支持子集参数(请参阅子集和子字符串),因此您可以像这样选择要处理/传递的参数。

  1. 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}"
    
  2. run it:

    $ chmod u+x r.sh
    $ ./r.sh 1 2 3 4 5 6 7 8 9 10
    
  3. 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
    
  1. 打开新文件并编辑它: 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}"
    
  2. 运行:

    $ chmod u+x r.sh
    $ ./r.sh 1 2 3 4 5 6 7 8 9 10
    
  3. 结果是:

    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