Bash Scripting – How to Escape a Single Quote in a Single-Quote String in Bash

bashescapinglinux

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 can I accomplish this while using single quotes around the string?

Best Answer

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.

Related Question