Shekhar Upadhaya Shekhar Upadhaya - 1 year ago 101
Bash Question

Escaping $ variable in sed over ssh command?

I have a command like this:

ssh user@hostname 'sed -e "s|foo|${bar}|" /home/data/base_out.sql > /home/data/out.sql'

The sed command is working in local shell. But it is not expanding the variable over ssh command. Thanks!

Answer Source

The rule is that within single quotes, parameters are not expanded. You have single quotes around the entire command.

Try this:

ssh user@hostname "sed -e 's|foo|$bar|' /home/data/base_out.sql > /home/data/out.sql"

Now $bar is expanded before the command string is passed as an argument to ssh, which is what you want.

I removed the curly braces around ${bar} because I believe they offer a false sense of security. In this case, they are not protecting you against any of the issues associated using shell variables in sed commands.