2

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?

Ronan Boiteau
  • 8,910
  • 6
  • 33
  • 52
Nomad
  • 939
  • 4
  • 15
  • 28

3 Answers3

3

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\''"'
choroba
  • 216,930
  • 22
  • 195
  • 267
0

Try removing the double quotes and escaping the single quotes:

/bin/bash -l -c "echo \'John\'"
Ronan Boiteau
  • 8,910
  • 6
  • 33
  • 52
0

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.)

tripleee
  • 158,107
  • 27
  • 234
  • 292