开发者

How to find compress method of archive in bash

I need to findout type (compress method) of archive in parametrs when call to my script and accord to compress method use tar with right options.

I find that file command return information about file so I can get 2nd column from that and use some condition and check what is it (I just need support tar -compressed by gzip or bzip2 not compressed and zip but I shouldn´t check by postfix but by content).

So i want to ask if there is better way to get c开发者_如何学JAVAompressed method of archive then by file and getting 2nd column. Thanks


Recent versions of GNU tar figures this out by itself so you don't have to, e.g. tar -xvf myarchive.tar.gz is enough

Otherwise use e.g. this:

function extract()
{
     if [ -f $1 ] ; then
         case $1 in
             *.tar.bz2)   tar xvjf $1     ;;
             *.tar.gz)    tar xvzf $1     ;;
             *.bz2)       bunzip2 $1      ;;
             *.rar)       unrar x $1      ;;
             *.gz)        gunzip $1       ;;
             *.tar)       tar xvf $1      ;;
             *.tbz2)      tar xvjf $1     ;;
             *.tgz)       tar xvzf $1     ;;
             *.zip)       unzip $1        ;;
             *.Z)         uncompress $1   ;;
             *.7z)        7z x $1         ;;
             *)           echo "'$1' cannot be extracted via >extract<" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

If you want to inspect the content, and care for only bzip2 or gzipped tar archives, do something like :

function extract() {
    if file $1 | grep bzip2 >/dev/null ; then
      tar -xvjf $1
    elif file $1 | grep gzip >/dev/null ; then
        tar -xvzf $1
    else
        echo "'$1' is not a valid file"
    fi
}


Your best choices are to either depend on file as you are now, or to look up the likely magic numbers (file type identifiers generally placed at the beginning of a file) and figure it out yourself.

For example, ZIP files start with "PK" and BZip2 files start with "BZ". These magic numbers may be longer, but that's what I noticed when looking at a couple a moment ago.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜