2

I'm trying to execute a ssh command executing a bash command on a remote host. My problem is that I want to pipe the result of another command inside of the execution.

ssh -i ~/keys/pem_key.pem [email protected] "sudo docker logs $(docker ps | grep 'test' | awk '{print$1}')"

The part of the command:

$(docker ps | grep 'test' | awk '{print$1}')

is not executed inside of execution.

Any way how this can be achieved?

AdminBee
  • 21,637
  • 21
  • 47
  • 71
david
  • 121
  • 5
  • @guest Thanks. Yes, the problem is with escaping the dollar, but in both parts. `\$(docker ps | grep 'test' | awk '{print\$1}')` – david Mar 03 '20 at 02:12
  • 1
    Related: https://unix.stackexchange.com/q/459923/237982 – jesse_b Mar 03 '20 at 02:31

2 Answers2

4

Although it is possible to get a command that needs complicated quoting passed through ssh argument(s) to the remote, it is often simpler to supply it as input instead:

 ssh -i ~/keys/pem_key.pem [email protected] <<'EOF'
 sudo docker logs $(docker ps | grep 'test' | awk '{print$1}')
 EOF

Note the here-doc delimiter 'EOF' is quoted; this causes the input to be passed without any change to the remote, which executes it. It can actually be any string that isn't in the input; EOF is just a customary and easy-to-type value. And you can use <<\EOF or <<"EOF" instead if you prefer.

Also note this particular case could be simplified to:

 ssh -i ~/keys/pem_key.pem [email protected] <<'EOF'
 sudo docker logs $(docker ps | awk '/test/{print$1}')
 EOF
dave_thompson_085
  • 3,790
  • 1
  • 16
  • 16
0

The solution is the following:

ssh -i ~/keys/pem_key.pem [email protected] "sudo docker logs \$(docker ps | grep 'test' | awk '{print\$1}')"
david
  • 121
  • 5