Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a single quote in single quote string in Bash?

I want to display a string in Bash like this

I'm a student 

Of course you can do it like this

echo "I'm a student" 

But how to accomplish this while using single quote around the string ?

like image 747
爱国者 Avatar asked Nov 24 '11 08:11

爱国者


People also ask

How do you escape a single quote from a single quote?

' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.

How do I escape a quote from a bash string?

Bash escape character is defined by non-quoted backslash (\). It preserves the literal value of the character followed by this symbol. Normally, $ symbol is used in bash to represent any defined variable.

How do I escape a single quote in Linux?

A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word.

How do you handle a single quote in a string?

Use escapeEcmaScript method from Apache Commons Lang package: Escapes any values it finds into their EcmaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.). So a tab becomes the characters '\\' and 't' .


1 Answers

echo 'I\'m a student' 

does not work. But the following works:

echo $'I\'m a student' 

From the man page of bash:

A single quote may not occur between single quotes, even when preceded by a backslash.
....
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

like image 156
codaddict Avatar answered Sep 29 '22 03:09

codaddict