--- title: 一键清理Portainer的compose脚本 date: 2024-12-15T10:30:43+08:00 lastmod: 2024-12-15T10:34:40+08:00 --- # 一键清理Portainer的compose脚本 ```bash #!/bin/bash # 定义 Compose 目录路径 查看portainer的挂载路径即可 COMPOSE_PATH="/path/to/compose" # 获取所有正在运行的容器的挂载路径 containers=$(docker ps -q) # 获取 Compose 目录下所有子目录 directories=$(find "$COMPOSE_PATH" -mindepth 1 -maxdepth 1 -type d) # 遍历每个子目录,检查是否被容器挂载 for dir_path in $directories; do in_use=false # 遍历所有容器,检查是否挂载该目录 for container in $containers; do mounts=$(docker inspect --format '{{range .Mounts}}{{.Source}} {{end}}' $container) # 检查该容器的挂载是否包括当前目录 if [[ "$mounts" == *"$dir_path"* ]]; then in_use=true break fi done # 输出检查结果 if [ "$in_use" = true ]; then echo "目录 $dir_path 正在被容器使用,无法删除。" else echo "目录 $dir_path 未被容器使用,可以安全删除。" # 提示用户是否删除 read -p "是否删除该目录?[Y/n] " user_input user_input=${user_input:-n} # 默认值为 'n',即跳过 if [[ "$user_input" == "Y" || "$user_input" == "y" ]]; then rm -rf "$dir_path" echo "目录 $dir_path 已被删除。" else echo "跳过删除 $dir_path。" fi fi done ```   ‍