feat(exec-docker): 增加对未启动容器的处理

- 修改容器查询命令,增加对容器状态的显示
- 添加判断逻辑,检测容器是否处于运行状态
- 如果容器未启动,提示用户是否要启动它
- 用户选择启动后,继续执行进入容器的操作
- 用户选择不启动,则退出脚本
This commit is contained in:
outmanwt 2025-03-12 19:33:39 +08:00 committed by GitHub
parent 39d0ca6294
commit fe74fbff63
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -10,7 +10,7 @@ else
fi
# 查找匹配关键词的容器
containers=$(docker ps --format "{{.ID}} {{.Image}} {{.Names}}" | grep "$keyword")
containers=$(docker ps -a --format "{{.ID}} {{.Image}} {{.Names}} {{.State}}" | grep "$keyword")
# 检查是否找到匹配的容器
if [ -z "$containers" ]; then
@ -24,6 +24,18 @@ container_count=$(echo "$containers" | wc -l)
if [ "$container_count" -eq 1 ]; then
# 只有一个匹配的容器,直接进入
container_id=$(echo "$containers" | awk '{print $1}')
container_state=$(echo "$containers" | awk '{print $4}')
if [ "$container_state" != "running" ]; then
read -p "容器 $container_id 未启动,是否要启动它?(y/n): " start_container
if [ "$start_container" = "y" ]; then
docker start $container_id
else
echo "未启动容器,退出"
exit 1
fi
fi
echo "找到一个匹配的容器,直接进入: $container_id"
docker exec -it $container_id /bin/bash
else
@ -34,6 +46,19 @@ else
# 提示用户选择一个容器ID
read -p "请输入要进入的容器ID: " container_id
# 获取选定容器的状态
container_state=$(docker inspect -f '{{.State.Status}}' $container_id)
if [ "$container_state" != "running" ]; then
read -p "容器 $container_id 未启动,是否要启动它?(y/n): " start_container
if [ "$start_container" == "y" ]; then
docker start $container_id
else
echo "未启动容器,退出"
exit 1
fi
fi
# 进入选定的容器
docker exec -it $container_id /bin/bash
fi
fi