[英]What's the purpose of the argument at the end of "bash -c command argument"?
从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 将 arguments 传递给多个命令的方法。 以下解决方案工作得很好(灵感来自这里),但我不明白为什么最后需要一个参数:
[编辑:按照chepner的回答,参数不需要为空,它确实可以是任何东西,但它必须存在]。
$ 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'
?
它不必是空引号(这是您提供空字符串作为具体值的方式)。 如果您实际上并不关心命令中$0
的值,它可以是任何值。 如果您确实关心,那么您将提供所需的值而不是空字符串。
但无论第一个参数是什么,它将用于设置$0
。 没有选项可以不设置$0
并将 arguments 应用于$1
等。
其他常见的“虚拟”值是_
、 sh
和bash
。
查看空参数和无参数之间区别的一种简单方法是使用set
命令,然后查看$#
的值。 一、无位置arguments:
$ set --
$ echo "$#"
0
现在,一个空参数
$ set -- ''
$ echo "$#"
1
我不明白
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.