我正在尝试启动一个/bin/bash -c
带有位置参数的脚本,但无法找出以下问题:
假设我有如下 test.sh:
#!/bin/bash
echo $0
echo $1
> ./test.sh a
./test.sh
a
> /bin/bash -c ./test.sh a
./test.sh
为什么第二个返回 $1 的空仓位参数?基于手册页:
-c 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.
似乎"a"至少应该分配给 0 美元,这不是我看到的。/bin/bash -c 'echo $0' a
按预期工作。谢谢!
-c
后面的字符串就像一个微型脚本,之后的参数以$0
、$1
、$2
等形式传递给它。例如:
$ bash -c 'echo "$0=$0, $1=$1, $2=$2"' zero one two
$0=zero, $1=one, $2=two
(注意:迷你脚本必须用单引号引起来;如果没有单引号,对$0
的引用将在它们传递给bash -c
命令之前由您的交互式 shell 扩展。
在您的情况下,迷你脚本运行另一个脚本(./test.sh
(,但不传递参数。如果你想传递它们,你可以做这样的事情:
$ bash -c './test.sh "$1" "$2"' zero one two
./test.sh
one
如果脚本费心在这里打印其$2
,它将得到"两个"。传递$0
没有帮助,因为对于一个真正的脚本,它会自动设置为用于运行脚本的实际命令。
bash [long-opt] [-abefhkmnptuvxdBCDHP] [-o option] [-O shopt_option]-c 字符串[参数...]
-c
后面应该跟一个字符串,所以你可以引用./test.sh a
如下:
$ /bin/bash -c "./test.sh a"
./test.sh
a
-c
选项不会收集 bash 命令的所有后续参数,而只是使用第一个非选项参数,在您的情况下,该参数是紧随其后的参数。我不明白你为什么要在这里使用-c
。我会把你的命令写成
/bin/bash test.sh a
由于在这种情况下,不涉及 PATH 搜索,因此您也可以省略./
部分。事实上,test.sh
在这里甚至不需要可执行。