bashshellescaping

Escaping dollar sign and curly brace in Bash


I'm making a script that needs to write ${somestring} to a file. The way I figured doing this was by escaping the dollar sign, but when it executes, the string ends up empty.

Is there a way to escape this correctly?

My code:

# \$\{somestring\} works, but leaves the \'s which I don't want.
myvar=("Yes I require multiple lines.
    Test \${somestring} test");

echo "$myvar" >> "mytest.conf";

Solution

  • Just use single quotes, so that ${} won't be interpreted:

    $ myvar=5
    $ echo 'this is ${myvar}'
    this is ${myvar}
    $ echo "this is ${myvar}"
    this is 5
    

    Note, though, that your approach is working (at least to me on Bash):

    $ myvar=("Yes I require multiple lines.
      test \${somestring} test");
    $ echo "$myvar" > a
    $ cat a
    Yes I require multiple lines.
      test ${somestring} test