“bash -c 命令参数”末尾的参数的目的是什么?

问题描述

来自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'

解决方法

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

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

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

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

$ 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...