0

Say there are 3 machine: 'local', 'A' and 'B'. Only 'local' and 'A' are connected and 'A' and 'B' are connected. And 'local' wants run commands on B via A.

# I run ssh A "ssh B commands" frequently, so a function is created for have clearer code.
run_on_B() {
  ssh A "ssh B \"$@\""
}

run_on_B 'echo export PATH=\\\$HOME/bin:\\\$PATH >> \$HOME/.bash_profile'

Is there a better way to run commands on a remote machine via ssh? I feel it is easy to make mistake to do escaping $HOME or $PATH here.

zwy
  • 139
  • 1
  • 7

1 Answers1

1

The question is not really about running remote commands but about quoting and multiple level of parsing. because the command is used to generate a script file.

If the final command to append to .bash_profile, can be

export PATH="$HOME/bin:$PATH"

the command to append file

echo 'export PATH="$HOME/bin:$PATH"' >> "$HOME"/.bash_profile

passing as literal just getting out and escaping single quotes '

run_on_B 'echo '\''export PATH="$HOME/bin:$PATH"'\'' >> "$HOME"/.bash_profile'

But function may be rewritten

run_on_B() {
    ssh A 'ssh B '\'"$1"\'
}
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36