What is the most aesthetic way to to escape a single quote within a single-quoted string in (ba)sh?

谁说我不能喝 提交于 2019-12-20 07:37:45

问题


In a (ba)sh script of mine, I have, for example:

MYVAR='Alice says: "Hello, Bob." But Bob isn't listening.'

This is a syntax error, since the ' in isn't ends the single-quoted string. I know I can fix this using

MYVAR='Alice says: "Hello, Bob." But Bob isn'"'"'t listening.'

But that is sooo ugly... what can I do instead? sh doesn't support

MYVAR='Alice says: "Hello, Bob." But Bob isn\'t listening.'

Which would have been tolerable, and switching to a double-quotes string is not an option for me.


回答1:


No, you can't embed a single quote inside a single quoted string in Bash (or korn shell). It is a feature of the language you have chosen. Inside single quotes there are no special characters, and that includes \.

This is a variation on one of your solutions, and it is ugly:

 echo 'Alice says: "Hello, Bob." But Bob isn'\''t listening.'

gives:

Alice says: "Hello, Bob." But Bob isn't listening.

Alternatively use a different language, like Perl or Python.




回答2:


A non-POSIX solution which is supported in bash, at least, is the following:

MYVAR=$'Alice says: "Hello, Bob." But Bob isn\'t listening.'

The $ causes escape processing.




回答3:


Using a HEREDOC is a good way to deal with this:

read MYVAR << \EOF
Alice says: "Hello, Bob." But Bob isn't listening.
EOF



回答4:


You could also use double quotes and escaping. I guess, it is simpler than change the language:

MYVAR="Alice says: \"Hello, Bob.\" But Bob isn't listening."

More information about escaping symbols in bash.




回答5:


I'm not sure why switching to $'...' is an option but switching to double quotes is not (presumably to prevent some sort of parameter expansion). But you don't need to double quote the entire string:

MYVAR='Alice says: "Hello, Bob." But Bob '"isn't"' listening.'


来源:https://stackoverflow.com/questions/15459055/what-is-the-most-aesthetic-way-to-to-escape-a-single-quote-within-a-single-quote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!