删除k8s 或者docker运行失败的脚本

bash 复制代码
vi  delete_exited_containers.sh
bash 复制代码
#!/bin/bash

# 列出所有停止的容器并存储到数组
list_exited_containers() {
    echo -e "\nStopped containers:"
    containers=()
    # 获取停止的容器信息并存入数组
    while IFS= read -r line; do
        containers+=("$line")
    done < <(docker ps -a --filter "status=exited" --format "{{.ID}} {{.Names}}")
    
    # 显示停止的容器列表
    for i in "${!containers[@]}"; do
        echo "[$i] ${containers[$i]}"
    done
}

# 删除指定的容器
delete_containers() {
    local indexes=("$@")
    for index in "${indexes[@]}"; do
        if [[ $index =~ ^[0-9]+$ ]] && [[ $index -lt ${#containers[@]} ]]; then
            container_info=${containers[$index]}
            container_id=$(echo "$container_info" | awk '{print $1}')
            echo "Deleting container: $container_info"
            docker rm "$container_id"
        else
            echo "Invalid index: $index"
        fi
    done
}

# 主逻辑
while true; do
    list_exited_containers

    if [[ ${#containers[@]} -eq 0 ]]; then
        echo "No stopped containers to delete."
        break
    fi

    # 获取用户输入
    echo -e "\nEnter indexes of containers to delete (space-separated), or type 'all' to delete all, or 'exit' to quit:"
    read -r input

    if [[ "$input" == "exit" ]]; then
        echo "Exiting..."
        break
    elif [[ "$input" == "all" ]]; then
        # 删除所有容器
        for i in "${!containers[@]}"; do
            container_id=$(echo "${containers[$i]}" | awk '{print $1}')
            echo "Deleting container: ${containers[$i]}"
            docker rm "$container_id"
        done
        echo "All stopped containers deleted."
    else
        # 使用下标删除指定的容器
        IFS=' ' read -r -a indexes <<< "$input"
        delete_containers "${indexes[@]}"
    fi

    echo -e "\nOperation complete. Would you like to continue? (yes/no):"
    read -r continue_input
    if [[ "$continue_input" != "yes" ]]; then
        echo "Exiting..."
        break
    fi
done

赋予执行权限

bash 复制代码
chmod +x delete_containers_by_index.sh

运行脚本

bash 复制代码
./delete_containers_by_index.sh

输入下标,然后输入yes确认删除

bash 复制代码
0
yes
相关推荐
lichenyang45311 小时前
Docker 学习笔记(五):Docker Compose,用一个 YAML 启动前端、后端和 MongoDB
docker
lichenyang45311 小时前
Docker 学习笔记(四):Dockerfile,把项目打成自己的镜像
docker·容器
lichenyang45311 小时前
Docker 学习笔记(三):Docker 网络、bridge、子网和容器互通
docker·容器
lichenyang45311 小时前
Docker 学习笔记(二):docker run 的参数到底在控制什么?
docker·容器
运维开发故事3 天前
基于 Arthas 的多集群在线诊断系统设计与实现
kubernetes
Patrick_Wilson5 天前
从「改个端口」到 502:Next.js on k8s 的容器端口、Service 映射与 env 覆盖
docker·kubernetes·next.js
探索云原生5 天前
K8s 1.36 这个 GA 特性,把 initContainer 拉模型的 hack 干掉了
ai·云原生·kubernetes
Suroy5 天前
DockerView-Go:用 Go 写一个终端 Docker 监控工具,顺便做了个 Web 仪表盘
docker
云恒要逆袭5 天前
运行你的第一个Docker容器
后端·docker·容器