如何在 Bash 中转义单引号字符串中的单引号?

发布于 2024-12-17 16:34:54 字数 240 浏览 1 评论 0原文

我想在 Bash 中显示一个字符串,如下所示:

I'm a student

当然你可以这样做:

echo "I'm a student"

但是如何在字符串周围使用单引号来完成此操作?

I want to display a string in Bash like this:

I'm a student

Of course you can do it like this:

echo "I'm a student"

But how can I accomplish this while using single quotes around the string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

决绝 2024-12-24 16:34:54
echo 'I\'m a student'

不起作用。但以下内容有效:

echo 

来自 Bash 的手册页:

单引号之间不能出现单引号,即使位于单引号前面
通过反斜杠。
....
$'string' 形式的单词会被特殊处理。这个词
扩展为字符串,反斜杠转义字符替换为
由 ANSI C 标准指定。

I\'m a student'

来自 Bash 的手册页:

单引号之间不能出现单引号,即使位于单引号前面
通过反斜杠。
....
$'string' 形式的单词会被特殊处理。这个词
扩展为字符串,反斜杠转义字符替换为
由 ANSI C 标准指定。

echo 'I\'m a student'

does not work. But the following works:

echo 

From the man page of Bash:

A single quote may not occur between single quotes, even when preceded
by a backslash.
....
Words of the form $'string' are treated specially. The word
expands to string, with backslash-escaped characters replaced as
specified by the ANSI C standard.

I\'m a student'

From the man page of Bash:

A single quote may not occur between single quotes, even when preceded
by a backslash.
....
Words of the form $'string' are treated specially. The word
expands to string, with backslash-escaped characters replaced as
specified by the ANSI C standard.

心如荒岛 2024-12-24 16:34:54

“丑陋”的解决方案格伦·杰克曼提到的实际上应该被列为顶级答案。它运作良好,并且在某些情况下实际上很漂亮。

'I'"'"'m a student'

这将结束 I 之后的单引号字符串,然后立即开始一个包含单引号的双引号字符串,然后开始另一个单引号字符串。然后 Bash 将所有连续的字符串连接成一个。

美丽的!

The "ugly" solution mentioned by Glenn Jackman should actually be listed as a top level answer. It works well and is actually beautiful in some situations.

'I'"'"'m a student'

This ends the single quoted string after I then immediately starts a double quoted string containing a single quote and then starts another single quoted string. Bash then concatenates all contiguous strings into one.

Beautiful!

吖咩 2024-12-24 16:34:54

下面的示例之所以有效,是因为转义的单引号 \' 从技术上讲位于两个单引号参数之间

echo 'I'\''m a student'

The example below works because the escaped single quote \' is technically between two single-quoted arguments

echo 'I'\''m a student'
刘备忘录 2024-12-24 16:34:54

另一种解决方法是使用 printf 代替 echo 并使用 \x27 转义所需的单引号:

printf 'I\x27m a student!\n'

Another way to workaround is to use printf instead echo and escape the required single quote with \x27:

printf 'I\x27m a student!\n'
甜是你 2024-12-24 16:34:54

我建议

echo“我是学生”

像其他语言一样

I propose

echo "I'm a student"

like in other languages.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文