2

I have this very reduced example of a bash command, where I want the $ sign escaped. So the command :

su -m user -c "echo $test"

should print out:

$test

a simple \$test does not work unfortunately. I tried lots of other stuff but still couldn't find a solution. Any suggestions ?

paddy3k
  • 149
  • 1
  • 11

1 Answers1

2

Put it in single quotes rather than double quotes.

su -m user -c 'echo \$test='

The single quotes keep the variable from being expanded by the original shell. The backslash then escapes the dollar sign in the shell run by su.

See Difference between single and double quotes in Bash

In answer to the comment, you can switch to double quoting to get single quotes into the string.

su -m user -c 'echo \$test='"'1'"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thx Barmar! I missed something important. How to express it when I want $test='1' as result? su -m user -c 'echo \$test=\'1\'' does not work – paddy3k Nov 19 '20 at 08:41
  • Thx again, but the output is still just $test=1 ... did I miss something ? If I flip the whole quotes to this : su -m user -c "echo "'\$'"test=\'1\'" it works and prints $test='1' – paddy3k Nov 19 '20 at 08:51
  • It's hard to read code in comments, put backticks around it to make it more readable. – Barmar Nov 19 '20 at 15:17
  • In general it's not easy to have nested command lines and nested quotes and escapes. Sometimes you need to double or triple the backslashes. – Barmar Nov 19 '20 at 15:19