【问题标题】:Print single quotes in shell script using option -c [duplicate]使用选项 -c 在 shell 脚本中打印单引号 [重复]
【发布时间】:2018-05-08 11:05:44
【问题描述】:

这听起来可能很新手,但我尽一切努力让它发挥作用。 我想用单引号打印一个单词: 'John' 在 shell 脚本中。我无法替换/bin/bash -l -c,因为这部分代码是由Java 运行的,我必须将shell 命令作为字符串传递。我也尝试了echo -e 选项。

/bin/bash -l -c 'echo "'John'"'

我想要的输出是:

'John'

我尝试转义单引号,但到目前为止没有任何帮助。有什么想法吗?

【问题讨论】:

    标签: linux bash shell unix echo


    【解决方案1】:

    你不能在bash中嵌套单引号,所以该行被解释为

    /bin/bash -l -c 'echo "'John'"'
                    |......| ---------- single quoted
                           |....| ----- not quoted
                                |.| --- quoted
    

    所以,正确地转义单引号:

    /bin/bash -c 'echo "'\''John'\''"'
    

    或者,如果单引号中的字符串真的很简单,

    /bin/bash -c 'echo "'\'John\''"'
    

    【讨论】:

      【解决方案2】:

      尝试删除双引号并转义单引号:

      /bin/bash -l -c "echo \'John\'"
      

      【讨论】:

        【解决方案3】:

        一种常见的解决方法是使用printf,这样您就不需要在格式字符串中使用文字单引号。

        bash -l -c 'printf "\x27John\x27\n"'
        

        (在此处使用 bash -l 可能会被误导且不可移植。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-10
          • 1970-01-01
          • 2019-01-22
          • 2012-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多