bash - 我似乎无法在 "-c"选项字符串之后使用带参数的 Bash "-c"选项

标签 bash eval

Bash 的手册页说,关于 -c选项:

-c <i>string</i> 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 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/

相关文章:

linux - 狂欢 : how to use a function (which is a string param) in an other function

linux - 使用点运行 shell 脚本为什么 "echo $0"打印 -bash

python - {元组 :NumPy. 数组} 的循环字典

lisp - 在使用 eval 和 quote 函数时需要帮助

php - 使用 eval 从字符串计算数学表达式

mysql - 从 mac 命令行将 .sql 文件导入 mysql。尝试 mysql -u root -p db_name > path/to/dbfile.sql

json - 使用jq添加JSON对象时如何防止转义?

javascript - 如何在 Node.js 中安全地执行未知的 Javascript 代码?

作为参数给出的 Bash 函数调用命令

linux - 如何创建由多个命令组成的别名?