Search code examples
linuxshellcompressionfish

fail to build universal compression function in fish


i am using fish shell on linux, i would like to write a function applicable to most compression file formats and what i wrote was:

function ex
    if test -f $argv[1]
        switch (file $argv[1])
            case '*.tar.bz2'
                tar xjf $argv[1]
            case '*.tar.gz' '*.tgz'
                tar xvf $argv[1]
            case '*.bz2'
                bunzip2 $argv[1]
            case '*.rar'
                unrar x $argv[1]
            case '*.gz'
                gunzip $argv[1]
            case '*.tar'
                tar xf $argv[1]
            case '*.tbz2'
                tar xjf $argv[1]
            case '*.zip'
                unzip $argv[1]
            case '*.Z'
                uncompress $argv[1]
            case '*.7z'
                7z x $argv[1]
        end
    else
        echo "'$argv[1]' is not a valid file"
    end
end

however when i apply this to a tar.gz file in fish shell, no error was given, but it was not extracted either. then when i tried to tar xjf the file,, it is extracted.

this has been confusing me for a while.


Solution

  • function ex
        if test -f $argv[1]
            set ext (echo $argv[1] | sed 's/.*\.\(tar\.bz2\|tar\.gz\|tgz\|bz2\|rar\|gz\|tar\|tbz2\|zip\|Z\|7z\)$/\1/')
            if test -n $ext
                switch $ext
                    case 'tar.bz2'
                        tar xjf $argv[1]
                    case 'tar.gz' 'tgz'
                        tar xvf $argv[1]
                    case 'bz2'
                        bunzip2 $argv[1]
                    case 'rar'
                        unrar x $argv[1]
                    case 'gz' ! 'tar.gz' 'tgz'
                        gunzip $argv[1]
                    case 'tar'
                        tar xf $argv[1]
                    case 'tbz2'
                        tar xjf $argv[1]
                    case 'zip'
                        unzip $argv[1]
                    case 'Z'
                        uncompress $argv[1]
                    case '7z'
                        7z x $argv[1]
                    case '*'
                        echo "Unknown file extension: $ext"
                end
            else
                echo "Unrecognized file format: $argv[1]"
            end
        else
            echo "'$argv[1]' is not a valid file"
        end
    end