Escaping quotes within variables is always painful in bash (somehow) – e.g.
foo”bar
and it’s not obvious that you’d need to write e.g.
“foo”\””bar”
(at least to me).
Thankfully a bash built in magical thing can be used to do the escaping for you.
In my case, I need to pass a ‘PASSWORD’ variable through to run within a container. The PASSWORD variable needs escaping so it can safely contain things like ; or quote marks (” or ‘).
e.g. docker compose run app /bin/bash "echo $PASSWORD > /some/file"
or e.g. ssh user@server “echo $PASSWORD > /tmp/something”
The fix is to use the ${PASSWORD@Q} variable syntax – for example:
#!/bin/bash
FOO=”bar’\”baz”
ssh user@server “echo $FOO > /tmp/something”
This will fail, with something like : “bash: -c: line 1: unexpected EOF while looking for matching `''
“
As she shell at the remote end it seeing echo bar'"baz
and expects the quote mark to be closed.
So using the @Q magic –
ssh user@server “echo ${FOO@Q} > /tmp/something”
which will result in /tmp/something containing “bar'”baz” which is correct.