在(ba)sh中用单引号引起来的单引号转义的最美学方法是什么?

在(ba)sh中用单引号引起来的单引号转义的最美学方法是什么?

问题描述:

在我的(ba)sh脚本中,例如:

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

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

这是语法错误,因为isn't中的'结束单引号字符串.我知道我可以使用

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.'

但是那太丑了...我该怎么办呢? sh不支持

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.

不,您不能在Bash(或korn shell)的单个带引号的字符串中嵌入单个引号.这是您选择的语言的功能.在单引号内没有特殊字符,其中包括\.

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.'

给予:

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

或者使用其他语言,例如Perl或Python.

Alternatively use a different language, like Perl or Python.