繁体   English   中英

在bash中将单引号与echo一起使用

[英]Using single quotes with echo in bash

我正在通过使用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中使用单引号的其他问题,但是它们似乎将单引号作为脚本的一部分。 在我的情况下,单引号是从回显传入的某些字符串的一部分。 我真的不明白如何在不导致以下错误的情况下将此特定字符串传递给bash:

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

这可能很简单,我只是很笨,但是经过一段时间的搜索后,我似乎无法弄清楚该如何针对我的特定情况。

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

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

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

你可以做:

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

这使:

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

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

另请参阅/bin/sh的POSIX规范

尝试这个:

echo -e 'Here you\x27re'

要么

echo "Here you're"

由于单引号可以用双引号字符串“简单地”进行,所以我通常这样做:

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

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

由于没有人提到它,因此可以在bash使用ANSI引号引起来的字符串,其中可以包含转义的单引号。 (请注意,单引号之前的$ 。)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM