远程主机上的Bash命令替换 [英] Bash command substitution on remote host

查看:65
本文介绍了远程主机上的Bash命令替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行一个ssh到远程主机上的bash脚本,并停止正在运行的单个docker容器.

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

但是,出现以下错误:

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

当我手动执行此操作(通过SSH到计算机,运行命令)时,一切都很好,但是当尝试通过脚本执行操作时,我得到了错误.我想我的命令替换语法不正确,我已经搜索并尝试了各种引号等,但无济于事.

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?

推荐答案

在启动Heredoc时使用<<'EOF'(或<<\EOF-仅引用第一个字符将具有相同的效果),以​​防止对其扩展进行评估本地.

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

第一个read消耗docker ps输出的第一行;第二个仅提取第一列-仅使用bash内置函数.

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

这篇关于远程主机上的Bash命令替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆