Bash command substitution on remote host [duplicat

2020-02-06 16:52发布

I'm trying to run a bash script that ssh's onto a remote host and stops the single docker container that is running.

#!/usr/bin/env bash

set -e

ssh <machine> <<EOF

container=$(docker ps | awk 'NR==2' | awk '{print $1;}')

docker stop $container

EOF

However, I get the following error:

stop.sh: line 4: docker: command not found

When I do this manually (ssh to the machine, run the commands) all is fine, but when trying to do so by means of a script I get the error. I guess that my command substitution syntax is incorrect and I've searched and tried all kinds of quotes etc but to no avail.

Can anyone point me to where I'm going wrong?

标签: linux bash ssh
1条回答
姐就是有狂的资本
2楼-- · 2020-02-06 17:36

Use <<'EOF' (or <<\EOF -- quoting only the first character will have the same effect) when starting your heredoc to prevent its expansions from being evaluated locally.


BTW, personally, I'd write this a bit differently:

#!/bin/sh -e
ssh "$1" bash <<'EOF'
{ read; read container _; } < <(docker ps)
docker stop "$container"
EOF

The first read consumes the first line of docker ps output; the second extracts only the first column -- using bash builtins only.

查看更多
登录 后发表回答