如何在 Bash 中转义单引号字符串中的单引号?
我想在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不起作用。但以下内容有效:
来自 Bash 的手册页:
does not work. But the following works:
From the man page of Bash:
“丑陋”的解决方案格伦·杰克曼提到的实际上应该被列为顶级答案。它运作良好,并且在某些情况下实际上很漂亮。
这将结束
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.
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!
下面的示例之所以有效,是因为转义的单引号
\'
从技术上讲位于两个单引号参数之间The example below works because the escaped single quote
\'
is technically between two single-quoted arguments另一种解决方法是使用
printf
代替echo
并使用 \x27 转义所需的单引号:Another way to workaround is to use
printf
insteadecho
and escape the required single quote with \x27:我建议
echo“我是学生”
。像其他语言一样
I propose
echo "I'm a student"
like in other languages.