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

前端 未结 5 1377
予麋鹿
予麋鹿 2021-01-26 06:23

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

5条回答
  •  感情败类
    2021-01-26 07:12

    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.

提交回复
热议问题