【问题标题】:Why “echo -e a\ b\ c” interprets '\' escapes but “echo -e $(cat file)” does not?为什么“echo -e a\ b\ c”解释“\”转义而“echo -e $(cat file)”不解释?
【发布时间】:2022-01-25 21:45:40
【问题描述】:

在linux命令行中,可以使用语法 command1 $(command2) 将 command2 的输出用作参数 对于命令 1。例如,如果我有一个文件test.txt 的内容 this\ is\ a\ test,我可以使用(在这种情况下是废话) echo $(cat test.txt) 回显cat test.txt 的输出。但是,这会解释转义序列 以一种奇怪的方式:命令的输出 echo -e this\ is\ a\ testthis is a test,而输出 echo -e $(cat test.txt)this\ is\ a\ test。转义序列不是 如此解释。有谁知道这是为什么?

【问题讨论】:

  • 基本上,您不能可靠地将命令的输出用作另一个命令的参数S;引用和转义不起作用,单词将被拆分。仅对于 single 参数,您可以可靠地使用 command "$(command2)"
  • 在一种情况下,反斜杠是在调用 echo 之前由 shell 解释的语法;另一方面,它们是文字数据,直接传递给echo

标签: bash command-line command-line-arguments


【解决方案1】:

使用set -x查看区别:

$ cat file
this\ is\ a\ test
$ set -x
$ echo -e this\ is\ a\ test
+ echo -e 'this is a test'
this is a test
$ echo -e 'this\ is\ a\ test'
+ echo -e 'this\ is\ a\ test'
this\ is\ a\ test
$ echo -e $(cat file)
++ cat file
+ echo -e 'this\' 'is\' 'a\' test
this\ is\ a\ test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多