Bash 的手册页说,关于 -c
选项:
-c <i>string</i>
If the-c
option is present, then commands are read fromstring
. If there are arguments after the string, they are assigned to the positional parameters, starting with$0
.
鉴于该描述,我认为这样的事情应该可行:
bash -c "echo arg 0: $0, arg 1: $1" arg1
但输出只显示以下内容,所以它看起来像 -c
之后的参数字符串未分配给位置参数。
arg 0: -bash, arg 1:
我正在运行一个相当古老的 Bash(在 Fedora 4 上):
[root@dd42 trunk]# bash --version GNU bash, version 3.00.16(1)-release (i386-redhat-linux-gnu) Copyright (C) 2004 Free Software Foundation, Inc.
我真的想执行一些带参数的 shell 脚本。我以为-c
看起来很有前途,因此出现了上述问题。我想知道如何使用 eval,但我不认为我可以将参数传递给 eval 之后的内容。我也愿意接受其他建议。
最佳答案
您需要使用单引号来防止在调用 shell 中发生插值。
$ bash -c 'echo arg 0: $0, arg 1: $1' arg1 arg2
arg 0: arg1, arg 1: arg2
或者转义双引号字符串中的变量。使用哪个可能完全取决于您要在代码片段中放入什么。
关于bash - 我似乎无法在 "-c"选项字符串之后使用带参数的 Bash "-c"选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1711970/