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

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

问题描述

我正在尝试运行一个 bash 脚本,该脚本通过 ssh 连接到远程主机并停止正在运行的单个 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

但是,我收到以下错误:

However, I get the following error:

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?

推荐答案

Use <<'EOF' (or <<EOF -- quoting只有第一个字符会具有相同的效果)在启动您的 heredoc 以防止其扩展在本地进行评估时.

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天全站免登陆