在bash中使用带有echo的单引号

时间:2014-09-01 14:55:58

标签: bash command-line

我正在使用echo和piping从命令行运行一些代码。 这是我尝试运行的代码行:

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

这可能很简单,我只是愚蠢但在寻找一段时间之后我似乎无法弄清楚如何针对我的特殊情况做这件事。

6 个答案:

答案 0 :(得分:4)

如果您对引号不确定,只需使用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")

答案 1 :(得分:3)

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

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

答案 2 :(得分:3)

你可以这样做:

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

给出了:

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

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

另见the POSIX spec of /bin/sh

答案 3 :(得分:1)

试试这个:

echo -e 'Here you\x27re'

echo "Here you're"

答案 4 :(得分:0)

由于单引号可以在双引号字符串中“明白”,我通常会这样做:

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

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

答案 5 :(得分:0)

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

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