关于 bash -c

我们知道 -c 的意思是 command,所以 bash -c 后面应该跟一个 command。连 bash 的 man page 中都这么说:

-c string If the -c option is present, then commands are read from string.
If there are arguments after the string, they are assigned to the positional parameters, starting with $0.
而实际上不对。我们看下面的例子:

% bash -c “echo a b c”
a b c
% bash -c echo a b c

% bash -cx “echo a”

  • echo a
    a

如果 -c 后面跟一个参数 string的话,那么第三个例子中的 -cx 应该会报错,找不到x这个命令,而实际上没有报错,也就是说,-c 和 -x 一样,后面不跟任何参数。

再看上面第二个例子中,为什么只有换行输出?手册中说,如果后面还有参数的话,那么它们被赋值给$0,$1,$2等等,也就是说,bash -c echo a b c,实际上只执行了 bash -c echo,所以只输出了换行!我们可以看更好的例子:

% bash -c ‘echo “$0 is $0, $1 is $1, $2 is $2”‘ foo bar biz
$0 is foo, $1 is bar, $2 is biz

% echo ‘echo “$0 is $0, $1 is $1, $2 is $2”‘ > /tmp/args
% chmod +x /tmp/args
% bash -c /tmp/args foo bar biz
$0 is /tmp/args, $1 is , $2 is

% bash -c ‘/tmp/args; echo $0 is $0, $1 is $1, $2 is $2’ foo bar biz
$0 is /tmp/args, $1 is , $2 is
$0 is foo, $1 is bar, $2 is biz