我是bash脚本的新手,我想编写一个名为unpack的脚本,如下所示:
unpack [-r] [-v] file [file...]
-v - verbose
-r - recursive - will traverse contents of folders recursively, performing unpack on each.
我需要确定使用哪种压缩方式,并对这些压缩类型执行解压缩。
假设文件名和扩展名没有意义-知道使用哪种方法的唯一方法是通过file
命令。我有4个拆箱选项gunzip, bunzip2, unzip, uncompress
所以我写了一个函数 execute_unpacking
exectute_unpacking(){
for FILE in "${@}"
do
local FILE_TYPE=$(file "${FILE}")
# How to get the compression type of the file?
case "${FILE_TYPE}" in
*bzip2) bunzip2 ${RECURSIVE} "${FILE}" ;;
*gzip) gunzip ${RECURSIVE} "${FILE}" ;;
*Zip) unzip ${RECURSIVE} ${FILE} ;;
*compress) uncomprees ${RECURSIVE} ${FILE} ;;
?) echo "${FILE} cannot be extarcted" ;;
esac
done
}
所以根据$(file ${FILE})
我需要检查Zip, bzip2, compress, gzip
这是正确的方法吗?(我不想使用外部工具,例如dtrx
)
编辑:例如,如果我有4个文件:
$(file -i archive) => archive: text/plain; charset=us-ascii
$(file -i archive.bz2) => archive.bz2: application/x-bzip2; charset=binary
$(file -i archvive.gz) =>archive.gz: application/x-gzip; charset=binary
$(file -i archive.cmpr) => archive.cmpr: application/x-compress; charset=binary
所以我需要分配给FILE_TYPE
变量4个选项gzip,compress,bzip2,txt
,然后在我的case
语句中相应地匹配那些模式
我会怎么做:
#!/bin/bash
set -v
case $1 in
*.tar) tar xvf "$1";;
*.tgz) tar zxvf "$1";;
*.tar.gz) tar zxvf "$1";;
*.xz) tar xJvf "$1";;
*.gz) gunzip "$1";;
*.zip) unzip "$1";;
*.rar) unrar x "$1";;
*tar.bz2) tar xjvf "$1";;
*.bz2) bzip2 -d "$1";;
*) echo >&2 "unknow $1"
exit 1
;;
esac
可以使用file -i
以下方法进行增强:
case $(file -i "$1") in
*/x-bzip2*) bzip2 -d "$1";;
*/gzip*) gunzip "$1";;
*/zip*) unzip "$1"";;
*/x-xz*) tar xJvf "$1";;
?) echo "File $1 cannot be extracted";;
esac
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句