17

如果我使用单引号,带有撇号(“不要”)的单词会很烦人:

'Don'"'"'t do that'

如果我使用双引号,美元符号和感叹号就会出错:

"It cost like \$1000\!"

我可以使用另一种引用吗?

编辑:我还应该补充一点,我想直接将此字符串作为命令行参数传递,而不是将其存储在变量中。为此,我尝试使用 DigitalRoss 的解决方案,

$ echo "$(cat << \EOF 
Don't $worry be "happy".
EOF)"

但得到

dquote cmdsubst> 

按回车后:/。所以此时 ZyX 的建议setopt rcquotes看起来是最方便的。

4

4 回答 4

22

With zsh you may do

setopt rcquotes

. Then ASCII apostrophes are escaped just like this:

echo 'Don''t'

. Or setup your keymap to be able to enter UTF apostrophes, they have no issues with any kind of quotes (including none) in any shell:

echo 'Don’t'

. Third works both for zsh and bash:

echo $'Don\'t'

.

Neither first nor third can narrow down quote to a single character, but they are still less verbose for non-lengthy strings then heredocs suggested above. With zsh you can do this by using custom accept-line widget that will replace constructs like 'Don't' with 'Don'\''t'. Requires rather tricky regex magic that I can write only in perl; and is probably not the best idea as I can’t pretend I can cover all possible cases before they will hit. It won’t in any case touch any scripts.

于 2012-10-14T19:10:13.150 回答
4

我喜欢Zsolt Botykai的发展方向。这是一个适用于任何 Posix shell 的示例。(我还验证了它在粘贴到 SO 服务器时仍然存在。)

$ read -r x << \EOF
Don't $worry be "happy".
EOF
$ echo $x
Don't $worry be "happy".

使这项工作发挥作用的东西;

  • -r不会\变魔术
  • \EOF不是只是EOF使$不是魔术
于 2012-10-14T18:19:56.780 回答
3

If you want to assign a quoted text to a variable, you still can use heredocs, like (and it can be a multiline text too):

read -r -d '' VAR <<'ENDOFVAR'
This "will be" a 'really well' escaped text. Or won't.
ENDOFVAR
于 2012-10-14T18:06:04.737 回答
1

Bash 语法$'string'是另一种引用机制,它允许类似 ANSI C 的转义序列并扩展为单引号版本。

$> echo $'Don\'t $worry be "happy".'
Don't $worry be "happy".

有关更多详细信息,请参阅https://stackoverflow.com/a/16605140/149221

于 2018-04-28T12:50:17.277 回答