bash - 在 bash 中执行命令时如何保留引号

标签 bash

我有一个 bash 脚本,其中包含类似于以下内容的内容:

cmd="grep 'a b'"

echo $cmd
$cmd

我遇到的问题是 $cmd 出于某种原因删除了 'a b' 周围的引号,并以 grep a b 的形式执行命令,导致错误:

% ./test.sh
grep 'a b'
grep: b': No such file or directory

我尝试了引号和转义的各种组合,但结果总是一样。

最佳答案

存储命令的最佳位置是在函数中。经验法则:变量用于数据;函数用于命令。

cmd() {
    grep 'a b'
}

...

cmd

关于bash - 在 bash 中执行命令时如何保留引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27004760/

相关文章:

php - php composer无法在public_html文件夹中访问

具有返回值和返回字符串的 bash 函数

bash - 使用 sed 提取大括号中的子字符串

bash - 连接行,对记录数取模

windows - 在 Windows 10 bash shell 中使用 conemu 时,为什么 UP 键不显示上一个命令?

linux - 如何验证shell中命令的输出?

bash - 需要对 kubectl stdin 和 pipeline 进行一些解释

windows - 来自 docker 容器的 ERR_EMPTY_RESPONSE

ruby - 读取 ruby​​ 中的所有 shell 变量

bash - 将绝对符号链接(symbolic link)转换为相对符号链接(symbolic link)