【问题标题】:Using single quotes with echo in bash在 bash 中使用带有 echo 的单引号
【发布时间】:2014-09-01 14:55:58
【问题描述】:

我正在使用 echo 和管道从命令行运行一些代码。 这是我要运行的代码行:

echo 'import Cocoa;println("It's over there")' | xcrun swift -i -v -

我尝试使用反斜杠来转义单引号,如下所示:

echo 'import Cocoa;println("It\'s over there")' | xcrun swift -i -v -

那行不通。
我已经看到有关在 bash 中使用单引号的其他问题,但它们似乎将单引号作为脚本的一部分。在我的例子中,单引号是从 echo 传入的某个字符串的一部分。我真的不明白如何将这个特定的字符串传递给 bash 而不会导致以下错误:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file

这可能很简单,我只是很愚蠢,但是在搜索了一段时间后,我似乎无法弄清楚如何针对我的特定情况执行此操作。

【问题讨论】:

    标签: bash command-line


    【解决方案1】:

    如果您不确定引号,只需使用 bash 的 heredoc 功能:

    cat <<'SWIFT' | xcrun swift -i -v -
    import Cocoa;println("It's over there")
    SWIFT
    

    如果你不加引号地使用它,例如SWIFT 代替 'SWIFT' 你可以在里面使用 bash 变量。

    最好是把它当作一个函数来使用,比如

    getcode() {
    cat <<SWIFT
    import Cocoa;println("It's over there $1")
    SWIFT
    }
    
    getcode "now" | xcrun swift -i -v -
    

    将发送到 xcrun 文本

    import Cocoa;println("It's over there now")
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      echo 'import Cocoa;println("It'\''s over there")'
      

      这给出了:

      import Cocoa;println("It's over there")
      

      请记住,在 bourne shell 中,echo 将输出整行,而引号只是“开始将其解释为文字”和“停止将其解释为文字”的标记,这与大多数编程略有不同语言。

      另见the POSIX spec of /bin/sh

      【讨论】:

      • 所以你引用了反斜杠?
      • @Johnston 不,这会停止引用字符串,输出 ',然后再次开始引用。
      • 啊哈,我明白了。显然有不止一种方法可以做到这一点。
      • @Johnston 是的 :) 所有提议的解决方案都符合标准且“良好”。出于可读性或其他原因,有些人可能更喜欢其中一个,但这确实是个人选择。
      【解决方案3】:

      在 BASH 中,您不能使用嵌套单引号或转义单引号。但是你可以像这样转义双引号:

      echo "import Cocoa;println(\"It's over there\")"
      import Cocoa;println("It's over there")
      

      【讨论】:

        【解决方案4】:

        试试这个:

        echo -e 'Here you\x27re'
        

        echo "Here you're"
        

        【讨论】:

        • 你需要使用echo -e "\x27"
        • @Carpetsmoker 哎呀,你是对的,我用 ZSH 测试过......我要添加 -e,zsh 让我更懒了......
        • 为什么是-e?我需要使用\x27re 还是\x27
        • @Johnston -e 可以解析echo 字符串中的特殊字符; tcshzsh 不需要,只有 bashsh\x27re 就是 're
        • @Johnston re is just abbrev. for 're (are),单引号是\x27。试一试,你会看到的。为什么-e,读人回声
        【解决方案5】:

        由于单引号可以“简单”地出现在双引号字符串中,所以我通常会这样做:

        echo 'import Cocoa;println("It'"'"'s over there")' | xcrun swift -i -v -
        

        即结束单引号字符串,开始一个只包含一个单引号的双引号字符串,结束双引号并开始一个新的单引号。

        【讨论】:

          【解决方案6】:

          由于没有其他人提到它,您可以在bash 中使用一个 ANSI 引用的字符串,它可以包含一个转义的单引号。 (注意单引号字符串前面的$。)

          echo $'import Cocoa;println("It\'s over there")' | xcrun swift -i -v -
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-06-16
            • 2013-12-05
            • 2012-04-27
            • 1970-01-01
            • 1970-01-01
            • 2016-01-22
            • 2021-11-30
            • 1970-01-01
            相关资源
            最近更新 更多