2

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
  • 66,199
  • 35
  • 114
  • 250
Wang
  • 1,212
  • 2
  • 15
  • 26

1 Answers1

1

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
  • 320,670
  • 36
  • 633
  • 936
  • how can I do the same thing with multiline command? in `ssh user@host bash < – 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