x3nr0s
x3nr0s

Reputation: 2158

Escaping two dollar signs at once

I have an SQL statement which I am running in my Bash script. It contains instances of two dollar signs in a row, for example:

psql -U $username -h $DATABASE_HOST $DATABASE_NAME -c "DO $$ DECLARE myVar varchar; END$$"

How can both of these be escaped?

Upvotes: 2

Views: 888

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74705

Just put a backslash in front of each one:

psql -U "$username" -h "$DATABASE_HOST" "$DATABASE_NAME" -c \
  "DO \$\$ DECLARE myVar varchar; END\$\$"

(Actually, since the second $ is followed by white space, the shell won't try to expand it, but the second backslash doesn't hurt).

Or, use single quotes around the string so that it is interpreted literally by the shell:

psql -U "$username" -h "$DATABASE_HOST" "$DATABASE_NAME" -c \
  'DO $$ DECLARE myVar varchar; END$$'

Like Biffen said in the comments, it's a good habit to always quote your variables.

If you're finding that the $$ is still being expanded, then I guess that this code is being parsed twice. In that case, you will need to either double-escape (\\\$\\\$) inside double quotes, or use \$\$ inside single quotes (or better yet, avoid parsing it twice if you don't need to).

Upvotes: 5

Related Questions