【问题标题】:What's the purpose of the argument at the end of "bash -c command argument"?“bash -c 命令参数”末尾的参数的目的是什么?
【发布时间】:2021-08-24 13:56:18
【问题描述】:

来自man bash

If the -c option is present, then commands are read from
the first non-option argument command_string.  If there
are arguments after the command_string, the first argument
is  assigned  to $0 and any remaining arguments are assigned
to the positional parameters. The assignment to $0 sets the
name of the shell, which is used in warning and error messages.

我不明白$0 分配的目的。

我正在探索使用 xargs 将参数传递给多个命令的方法。以下解决方案工作得很好(灵感来自here),但我不明白为什么最后需要一个参数:

[编辑:在chepner's answer之后,参数不需要为空,它可以是任何东西,但它必须存在]。

$ cat test
abc
def
ghi

$ cat test | xargs -n 1 /bin/bash -c 'echo "1-$@"; echo "2-$@";' 'dummyArgument'
1-abc
2-abc
1-def
2-def
1-ghi
2-ghi

显然'dummyArgument'bash -c 能够解释$@ 所必需的(它甚至可以为空''),因为没有它我会得到以下结果:

$ cat test | xargs -n 1 /bin/bash -c 'echo "1-$@"; echo "2-$@";'
1-
2-
1-
2-
1-
2-

但是它是如何工作的呢?为什么我需要那个'dummyArgument'

【问题讨论】:

    标签: bash shell arguments command single-quotes


    【解决方案1】:

    它不必是空引号(这是您提供空字符串作为具体值的方式)。它可以是 any 值,如果您实际上并不关心命令中 $0 的值。如果您确实关心,那么您将提供所需的值而不是空字符串。

    但无论第一个参数是什么,它都将用于设置$0。无法选择不设置 $0 并将参数应用于 $1 等。

    其他常见的“虚拟”值是_shbash

    查看空参数和无参数之间区别的简单方法是使用set 命令,然后查看$# 的值。首先,没有位置参数:

    $ set --
    $ echo "$#"
    0
    

    现在,一个空参数

    $ set -- ''
    $ echo "$#"
    1
    

    【讨论】:

    • 好的,我明白了。是的,我测试过,参数不必为空,它可以是任何字符串。但我还是不明白为什么bash -c 在命令字符串之后需要一个参数才能解释$@
    • 我更新了我的问题。既然我知道参数不必为空,我真正的问题实际上是:为什么我们需要 'dummyArgument'
    • 指定$0 的值根本不是可选的。如果您决定提供一个值,则没有像 -0 这样的单独选项可供使用; $0$1 等只需使用给定的位置参数按给定的顺序设置即可。如果您不考虑这一点,那么您认为是用于$1 的值实际上将分配给$0,等等。
    【解决方案2】:

    我不明白$0 分配的目的。

    它的目的是让你给你的内联脚本一个名字,可能是为了装饰诊断信息。没有什么有趣的。

    $ cat foo.sh
    echo my name is $0
    $
    $ bash foo.sh a b c
    my name is foo.sh
    $
    $ bash -c 'echo my name is $0' foo a b c
    my name is foo
    

    【讨论】:

    • 是的,我明白了。 xargs 有助于区分传递给 bash -c 的不同参数。无论如何,如果有人偶然发现这篇文章有同样的问题,比较以下命令的输出将有助于理解发生了什么:$ echo foo bar baz | xargs bash -c 'echo $0 - $@'$ echo foo bar baz | xargs bash -c 'echo $0 - $@' 'dummy'。再次感谢,您为我指明了正确的方向
    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2011-07-05
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多