[英]What's the purpose of the argument at the end of "bash -c command argument"?
From man bash
:从
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.
I don't understand the purpose of the $0
assignment.我不明白
$0
分配的目的。
I was exploring ways to pass arguments to multiple commands with xargs.我正在探索使用 xargs 将 arguments 传递给多个命令的方法。 The following solution works just fine (inspired from here ), but I fail to understand why an argument is needed at the end:
以下解决方案工作得很好(灵感来自这里),但我不明白为什么最后需要一个参数:
[ Edit: following chepner's answer , the argument doesn't need to be empty, it can be anything indeed, but it has to exist ]. [编辑:按照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
Obviously the 'dummyArgument'
is necessary for bash -c
to be able to interpret $@
, (it can even be empty ''
) because without it I get the following result:显然,
'dummyArgument'
是bash -c
能够解释$@
所必需的,(它甚至可以是空''
)因为没有它我得到以下结果:
$ cat test | xargs -n 1 /bin/bash -c 'echo "1-$@"; echo "2-$@";'
1-
2-
1-
2-
1-
2-
But how does it work?但它是如何工作的? Why do I need that
'dummyArgument'
?为什么我需要那个
'dummyArgument'
?
It doesn't have to be empty quotes (which is how you provide an empty string as a concrete value).它不必是空引号(这是您提供空字符串作为具体值的方式)。 It can be any value, if you don't actually care about the value of
$0
in your command.如果您实际上并不关心命令中
$0
的值,它可以是任何值。 If you do care, then you would provide the value you want instead of an empty string.如果您确实关心,那么您将提供所需的值而不是空字符串。
But whatever the first argument is, it will be used to set $0
.但无论第一个参数是什么,它将用于设置
$0
。 There is no option to leave $0
unset and apply the arguments to $1
et al intead.没有选项可以不设置
$0
并将 arguments 应用于$1
等。
Other common "dummy" values are _
, sh
, and bash
.其他常见的“虚拟”值是
_
、 sh
和bash
。
An easy way to see the difference between an empty argument and no argument is to use the set
command, then look at the value of $#
.查看空参数和无参数之间区别的一种简单方法是使用
set
命令,然后查看$#
的值。 First, no positional arguments:一、无位置arguments:
$ set --
$ echo "$#"
0
Now, a single empty argument现在,一个空参数
$ set -- ''
$ echo "$#"
1
I don't understand the purpose of the
$0
assignment.我不明白
$0
分配的目的。
Its purpose is to let you give your inline script a name, potentially for decorating diagnostic messages.它的目的是让你给你的内联脚本一个名字,可能是为了装饰诊断消息。 There is nothing interesting about it.
没有什么有趣的。
$ 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.