Shell – How to Echo Single Quote When Using Single Quote in Shell

quotingshell

I'm reading shell tutorial today from http://www.tutorialspoint.com/unix/unix-quoting-mechanisms.htm

In which it mentions:

If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you whould preceed that using a backslash () as follows:

echo 'It\'s Shell Programming'

I tried this on my centos server, it doesn't work, a > prompts out to hint me type more.

I was wondering, since two single quotes transform every special characters into normal characters, which include escape symbol \, but exclude itself, the ',
how should I represent a single single quote 'in a single-quoted phrase?

Best Answer

The tutorial is wrong.

POSIX says:

A single-quote cannot occur within single-quotes.

Here's some alternatives:

echo $'It\'s Shell Programming'  # ksh, bash, and zsh only, does not expand variables
echo "It's Shell Programming"   # all shells, expands variables
echo 'It'\''s Shell Programming' # all shells, single quote is outside the quotes
echo 'It'"'"'s Shell Programming' # all shells, single quote is inside double quotes

Further reading: Quotes - Greg's Wiki