删除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
相关推荐
让美好继续发生29 分钟前
解决docker报Error response from daemon Get httpsregistry-1.docker.iov2错误
运维·docker·容器
Seal软件37 分钟前
配置NVIDIA Container Runtime和容器运行GPUStack教程
docker·容器·大模型·llm·gpu集群
GPUStack38 分钟前
配置NVIDIA Container Runtime和容器运行GPUStack教程
docker·容器·大模型·llm·gpu集群
Labiod4 小时前
ffmpeg+ZLmeadiakit+ubuntu 服务器 推流
docker
Elastic 中国社区官方博客6 小时前
使用 Elastic 3 步实现基于 OTel 的原生 K8s 和应用可观测性
大数据·人工智能·elasticsearch·搜索引擎·云原生·容器·kubernetes
行者Sun19896 小时前
【K8s】专题十五(3):Kubernetes 网络之 Calico 插件理论
云原生·容器·kubernetes·cni·calico
fareast_mzh13 小时前
no matching manifest for linux/amd64 in the manifest list entries
docker·arm·raspberry·busybox
mit6.82413 小时前
[Docker#8] 容器配置 | Mysql | Redis | C++ | 资源控制 | 命令对比
linux·后端·docker·云原生·架构
梦想与想象-广州大智汇15 小时前
docker安装宝塔,Mac也可以使用宝塔搭建开发环境了
macos·docker·容器·php·宝塔