用ShellScript脚本来批量解压文件

写一个shellscript来解压指定文件夹下指定格式的压缩文件

之前呢,看过一点儿shellscript的知识,但是我平常并不做Linux服务器的运维管理,所以就用的比较少,看得也是马马虎虎,心想命令嘛,我一行一行敲就行了,就比如解压个文件,不就是一条命令解决的嘛,但是最近有个学习视频,一个文件夹里面有几十个压缩文件,这尼玛一条一条得解到啥时候,果断回过头来看ShellScript,六十行代码完成,命令还是比较基础的,就是一个循环语句嘛。但是在这之前,有必要说一下Linux系统下的解压工具,具体请看:Linux系统下的打包压缩及解压缩,通过我的使用,我觉得unar是一个相当不错的工具,zip也可以,rar也可以,而且之前unzip解压有些从Windows系统拷贝过来的.zip文件时,会有乱码问题,使用unar工具是没有这个问题的,所以我还是推荐使用unar工具来解压.zip和.rar文件,但是tar包的文件还是用tar命令最好些。

废话不多说,代码如下:

#!/bin/bash

# Program:
# Decompress files script
# History:
# 2020/06/03	aerlee	First release
# 2020/06/05	aerlee	second release
# The last release, and in this new relese, user can choose the  directory where 
# their compressed files and compressed types are.

# The user enter the directory where the compressed files are
read -p "Please enter a directory where the compressed files are : " dir
# Change the path to the directory
cd $dir
# Check if the directory is exist
if [ "$dir" == "" -o ! -d "$dir" ]; then
	echo "The $dir is NOT exist in your system."
	exit 1
fi
# The user enter the compressed format type 
read -p "Please enter the compressed format (like ".rar"): " type
# List all the files that matched
filelist=$(ls $dir | grep $type)
# Check if the directory and type user entered exist
if [ ! $filelist ]; then
	echo "There is NOT any file matchs your enter."
	echo "So please check your enter or your file's path."
fi
echo "Decompressing process running, good luck."
# It's a loop to traverse each compressed file that matched
if [ "$type" == ".rar" ]; then
	for filename in $filelist
	do
		unar $filename
	done
	echo "Decompress successfull !"
elif [ "$type" == ".zip" ]; then
	for filename in $filelist
	do
		unar $filename
	done
	echo "Decompress successfull !"
elif [ "$type" == ".tar.bz" ]; then
	for filename in $filelist
	do
		# To decompress each file
		tar -jxv -f "$filename" 
	done
	echo "Decompress successfull !"
elif [ "$type" == ".tar.gz" ]; then
	for filename in $filelist
	do
		tar -zxv -f $filename
	done
	echo "Decompress successfull !"
elif [ "$type" == ".gz" ]; then
	for filename in $filelist
	do
		gzip -d $filename
	done
	echo "Decompress successfull !"
elif [ "$type" == ".bz2" ]; then
	for filename in $filename
	do
		bzip2 -d $filename
	done
	echo "Decompress successfull !"
fi
exit 0

最后,我在写脚本过程中踩过的坑有必要记录一下:

  1. 刚开始,老是显示打开文件失败,想了一整天没想明白,最后通过file命令debug想看看获取到的是个什么文件类型时,显示没有找到文件,所以是获取到了文件名而在当前文件夹没有找到该文件,是因为没有切换到文件所在的文件夹,而解压命令是直接写的文件名而不是绝对路径,所以能打开文件才是见了鬼了。

  2. if语句后面的判断符号“[ ]”,也就是中括号,使用时需要注意以下几点:
    1).中括号两端需要有空格
    2).中括号内的每个组件都需要空格来分隔
    3).中括号内的变量和变量,最好都以双引号包起来

  3. if语句里面的或,也就是“||”竟然搞不了,可能是我哪里搞错了,不过我给拆成两个判断了,不影响运行结果。完了有待仔细研究一下,再来补充。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凉拌糖醋鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值