MST

星途 面试题库

面试题:Bash下用gunzip与bunzip2处理批量压缩文本文件

假设当前目录下有大量以.gz和.bz2结尾的文本压缩文件,编写一个Bash脚本,使用gunzip和bunzip2分别对这些文件进行解压,并处理解压过程中可能出现的文件覆盖、解压失败等异常情况。
22.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

for file in *.gz *.bz2; do
    if [[ $file == *.gz ]]; then
        if [ -e "${file%.gz}" ]; then
            echo "文件 ${file%.gz} 已存在,将不会覆盖。"
        else
            gunzip "$file" 2>/dev/null
            if [ $? -ne 0 ]; then
                echo "解压 $file 失败。"
            fi
        fi
    elif [[ $file == *.bz2 ]]; then
        if [ -e "${file%.bz2}" ]; then
            echo "文件 ${file%.bz2} 已存在,将不会覆盖。"
        else
            bunzip2 "$file" 2>/dev/null
            if [ $? -ne 0 ]; then
                echo "解压 $file 失败。"
            fi
        fi
    fi
done