Bash 脚本进入 运行ning 容器,然后 运行 来自该容器的另一个 bash 脚本

Bash script to get into a running container and then run another bash script from that container

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

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

当我从基础 linux OS 运行 执行此操作时,我希望实际进入 postgres 容器,它是一个 运行ning 容器。但问题是 shell 脚本在“docker exec”步骤中挂在第 3 行。

我的最终目标是使用 bash 脚本,在该容器中输入一个 运行ning 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