Bash 脚本进入正在运行的容器,然后从该容器运行另一个 bash 脚本

标签 bash postgresql shell docker dockerfile

我有一个运行如下的 shell 脚本:

image_id=$(docker ps -a | grep postgres | awk -F' ' '{print $1}')
full_id=$(docker ps -a --no-trunc -q | grep $image_id)
docker exec -i -t $full_id bash

当我从基本 linux 操作系统运行它时,我希望实际进入 postgres 容器,它是一个正在运行的容器。但问题是 shell 脚本在“docker exec”步骤期间卡在第 3 行。

我的最终目标是使用 bash 脚本,进入一个正在运行的 postgres 容器并在该容器内运行另一个 bash 脚本。 但是,当我从命令行运行相同的命令时,它工作正常并让我进入 postgres 容器。

请帮忙,我花了好几个小时来解决这个问题,但没有任何进展。

再次感谢

最佳答案

您的设置比需要的要复杂一些。

docker ps可以直接用--filter=选项

过滤容器
docker ps --no-trunc --quiet --filter="ancestor=postgres"

您也可以--name当您运行它们时容器将比您尝试的脚本充满危险

docker run --detach --name postgres_whatever postgres
docker exec -ti postgres_whatever bash

我不确定您的脚本是挂起还是坐在那里等待输入。尝试直接运行命令

使用命名

exec_test.sh

#!/usr/bin/env bash
docker exec postgres_whatever echo "I have run the test"

运行时

$ ./exec_test.sh
I have run the test

没有命名

exec_filter_test.sh

#!/usr/bin/env bash
id=$(docker ps --no-trunc --quiet --filter="ancestor=postgres")
[ -z "$id" ] && echo "no id" && exit 1
docker exec "${id}" echo "I have run the test"

运行时

$ ./exec_filter_test.sh 
I have run the test

关于Bash 脚本进入正在运行的容器,然后从该容器运行另一个 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948423/

相关文章:

bash - 如何从 kubectl 转发 psql shell

ruby-on-rails - 如何解决 Rails、GeoRuby(和 postgis/postgresql): NameError: uninitialized constant Point?

sql - 请解释为什么脚本以这种方式工作

regex - 使用 sed 转义正则表达式

regex - 如何测试字符串是否与 POSIX shell 中的正则表达式匹配? (不是 bash )

linux - 我怎样才能用grep得到一个完整的词?

c 执行不起作用

bash - awk 命令对行求和并在特定条件下过滤掉

linux - 后台进程在 Linux 上完成工作后的清理

linux - 通过脚本验证 sudoing 密码