使用单引号将特殊字符包装在 shell 中时如何回显“单引号”?

Zen*_*Zen 35 shell quoting

我今天从http://www.tutorialspoint.com/unix/unix-quoting-mechanisms.htm阅读 shell 教程

其中提到:

如果要输出的字符串中出现单引号,则不应将整个字符串放在单引号内,而应在其之前使用反斜杠 (),如下所示:

echo 'It\'s Shell Programming'
Run Code Online (Sandbox Code Playgroud)

我在我的 centos 服务器上试过这个,它不起作用,>提示提示我输入更多。

我想知道,由于两个单引号将每个特殊字符转换为普通字符,其中包括转义符号\,但排除自身,'
我应该如何'在单引号短语中表示单引号?

Mik*_*kel 63

教程错了。

POSIX说:

单引号内不能出现单引号。

这里有一些替代方案:

echo $'It\'s Shell Programming'  # ksh, bash, and zsh only, does not expand variables
echo "It's Shell Programming"   # all shells, expands variables
echo 'It'\''s Shell Programming' # all shells, single quote is outside the quotes
echo 'It'"'"'s Shell Programming' # all shells, single quote is inside double quotes
Run Code Online (Sandbox Code Playgroud)

进一步阅读:行情 - Greg's Wiki

  • 我有时会使用 `q="'"` 和 `qq='"'` 来使这个更简洁。然后允许 `echo "It${q}s ${qq}Shell Programming${qq}"`(大括号需要给定尾随字母)。POSIX 安全。外层必须用双引号引起来。 (6认同)
  • 还有一个:`echo 'It's Shell Programming'` - 设置了 `rc_quotes` 选项的 zsh(以及 rc shell) - 单引号内的一对单引号表示一个单引号。 (4认同)