Print single quotes in shell script using option -c

Viewed 1327

This may sound novice but I tried everything to get this to work. I want to print a word with single quotes : 'John' in shell script. I cant replace /bin/bash -l -c as this part of code is run by Java and I have to pass the shell command as a string. I tried with echo -e option as well.

/bin/bash -l -c 'echo "'John'"'

The output I want is:

'John'

I tried escaping the single quotes but nothing helped so far. Any ideas?

3 Answers

You can't nest single quotes in bash, so the line is interpreted as

/bin/bash -l -c 'echo "'John'"'
                |......| ---------- single quoted
                       |....| ----- not quoted
                            |.| --- quoted

So, properly escape the single quotes:

/bin/bash -c 'echo "'\''John'\''"'

or, if the string in single quotes is really simple,

/bin/bash -c 'echo "'\'John\''"'

Try removing the double quotes and escaping the single quotes:

/bin/bash -l -c "echo \'John\'"

A common workaround is to use printf so you don't need to use literal single quotes in the format string.

bash -l -c 'printf "\x27John\x27\n"'

(Using bash -l here is probably misdirected and nonportable.)

Related