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
  • 9,608
  • 6
  • 34
  • 56
Nomad
  • 1,019
  • 4
  • 16
  • 30

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
  • 231,213
  • 25
  • 204
  • 289
0

Try removing the double quotes and escaping the single quotes:

/bin/bash -l -c "echo \'John\'"
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
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
  • 175,061
  • 34
  • 275
  • 318