Bash – How to print “$” in here-document

bashquotingshell

How can I echo "$" in a here-doc in bash?

For example, I want to have a file with the content on remote server like $ABC=home_dir.

$ ssh hostname sudo -s <<EOF
echo "$ABC=home_dir" > file
EOF

But it would be treated as a variable. How can I print a literal $?

Best Answer

If you want to write a here-doc and you don't want ANY of the doc to be expanded or any special characters interpreted, you can quote the label with single quotes, like this:

$ cat >file <<'EOF'
echo "$ABC=home_dir"
EOF

However, your situation as described in your example is much more complex, because you're really sending this content through ssh, to a remote system, to be run by sudo which is also invoking a shell (and so that shell will expand the content as well). You're going to need more levels of quoting to get this right, but even with that it still won't work because sudo requires a terminal (so it can ask for a password) and you've redirected from stdin. Even using ssh -t won't help here.

Also I agree with Johan. It's not clear this is really what you want; note that it's not legal to assign a value to a shell variable reference, so if this file you're trying to create is supposed to be a shell script, it won't work as you've described it. Maybe if you back up a bit and describe what you really want to do, we can help more.