#!/bin/sh
#***************************************************************#
# ScriptName: docker_export_all_images.sh
# Author: xhy
# Create Date: 2025-03-09 03:45
# Modify Author: xhy
# Modify Date: 2025-08-27 13:40
# Version: v1
#***************************************************************#

# 创建导出目录
IMAGEDIR=/root/images
mkdir -p ${IMAGEDIR}

# 直接遍历所有镜像（跳过表头）
docker images | grep -v REPOSITORY | while read line; do
    # 提取镜像名和标签（兼容空格和特殊字符）
    repo=$(echo "${line}" | awk '{print $1}')
    tag=$(echo "${line}" | awk '{print $2}')
    
    # 跳过无效镜像
    if [[ "${repo}" == "<none>" || "${tag}" == "<none>" ]]; then
        continue
    fi

    # 生成文件名（替换特殊字符）
    safe_repo=$(echo "${repo}" | tr '/' '_' | tr ' ' '_')
    safe_tag=$(echo "${tag}" | tr '/' '_' | tr ' ' '_')
    filename="${safe_repo}_${safe_tag}.tar"
    
    # 导出镜像
    echo -e "\n\033[33m[INFO] 正在导出镜像: ${repo}:${tag} 至 ${IMAGEDIR} ...\033[0m"
    docker save -o "${IMAGEDIR}/${filename}" "${repo}:${tag}"
done

    echo -e "\n\033[32m[SUCC] 所有镜像已导出至 ${IMAGEDIR} 目录...\033[0m"
