3

I expect following this command to expand the HOME variable on the remote server:

ssh user@host bash -c "'echo ${HOME}'"

but instead this is expanded locally.

How do I get the remote HOME variable?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Wang
  • 1,296

1 Answers1

2

If the purpose is to just get the remote value of the HOME environment variable, it would be easier to do

ssh user@host printenv HOME

This would work as long as the remote shell or system has the printenv utility.


The HOME variable is being expanded locally because it is in a double-quoted string.

Instead, do either

ssh user@host 'bash -c "echo \"\$HOME\""'

or

ssh user@host 'bash -c '"'"'echo "$HOME"'"'"

In the first case above, the remote shell gets the command

bash -c "echo \"\$HOME\""

to execute.

In the second, it gets

bash -c 'echo "$HOME"'

If your local shell is zsh or bash, then you can use the %q format specifier of printf to construct a properly quoted string for the remote shell:

ssh user@host "$( printf '%q ' bash -c 'echo "$HOME"' )"

This also works for multi-line commands:

ssh user@host "$( printf '%q ' bash -c '
echo "home: $HOME"
echo "away: $AWAY"' )"

See also:

Kusalananda
  • 333,661
  • how can I do the same thing with multiline command? in ssh user@host bash <<END – Wang Feb 12 '21 at 15:46
  • @Wang Your example is not a complete command. If you want to run a script, then transfer it over and run it. Otherwise, you may use printf as I showed in my answer. – Kusalananda Feb 12 '21 at 15:54
  • @Wang Assuming you don't need to do any user interaction in your script, then just let the remote shell read the commands. If the remote shell is bash, then it should be enough with redirecting into ssh user@host (no special invocation of bash necessary). – Kusalananda Feb 12 '21 at 16:08