shell脚本,遍历文件进行压缩或解压

需求:将目录中文件夹(压缩包)进行批量压缩(解压)
批量压缩文件
#!/bin/bash

echo "----zip file----"
pwd_path=`pwd`

if [[ $1 == /* ]] ;then 
zip_target=$1"_zip" 
else 
zip_target=$pwd_path"/"$1"_zip" 
fi

echo "将 $1 目录下的文件逐个压缩,压缩后存放到路径 $zip_target 中"
if [ ! -d $zip_target ]; then 
mkdir -p $zip_target 
fi

function zip_file(){
for file in `ls $1`
do
if [ -d $1"/"$file ]; then 
cd $1
tar zcvf $zip_target"/"$file.tar.gz $file
cd $pwd_path
fi
done
}
zip_file $1

示例:
shell脚本,遍历文件进行压缩或解压_第1张图片
调用方法:
如上图,执行 sh zip.sh test
shell脚本,遍历文件进行压缩或解压_第2张图片

批量解压文件
#!/bin/bash

echo "----unzip file----"
pwd_path=`pwd`

if [[ $1 == /* ]] ;then 
unzip_target=$1"_unzip" 
else 
unzip_target=$pwd_path"/"$1"_unzip" 
fi

echo "将 $1 目录下的压缩文件逐个解压,解压后存放到目录 $unzip_target 中"
if [ ! -d $unzip_target ]; then 
mkdir -p $unzip_target 
fi

function unzip_file(){
for file in `ls $1`
do
if [[ $1"/"$file == *tar.gz ]]; then 
tar zxvf $1"/"$file -C $unzip_target
fi
done
}

unzip_file $1

示例:
将 test_zip 目录中的压缩文件解压,执行 sh unzip.sh test_zip
shell脚本,遍历文件进行压缩或解压_第3张图片

你可能感兴趣的:(linux学习笔记)