【问题标题】:Why is shell interpreting characters within single quotes?为什么shell解释单引号内的字符?
【发布时间】:2011-10-30 14:59:34
【问题描述】:

我正在使用 bash shell

$cat test
a --b

$grep '--b' test
grep: option `--b' is ambiguous
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.

$grep "--b" test
grep: option `--b' is ambiguous
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.

$grep '\-\-b' test
a --b

第 7 章“输入和输出、文件和命令评估”中的经典 shell 脚本书第 7.7 节引用说

“单引号强制外壳按字面意思处理双引号之间的所有内容”。

那为什么上面的单引号不起作用?

【问题讨论】:

    标签: linux bash shell unix scripting


    【解决方案1】:

    外壳按字面意思对待它们。但是shell 不负责应用程序 如何处理它们。由应用程序决定如何处理作为参数传递的--b

    【讨论】:

    • 没错。对于grep,您还可以使用grep -e --b test 匹配文件--b 中的test
    • 是的,grep 在其argv[1] 中看到 3 个字符的字符串“--b”。它不知道,也不可能知道参数在命令行中被引用或转义。
    【解决方案2】:

    大多数 gnu 实用程序在 -- 之后会忽略 --options,因此您可能想要改为使用 grep -- --b test。而且由于您标记了您的问题linux,因此您很可能拥有 gnu grep。

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 2010-10-03
      相关资源
      最近更新 更多