FishShell: Create & Expand compressed archives

FishShell: Create & Expand compressed archives

Tags
Computer Science
Software Development
Tips & Tricks
Published
December 21, 2013
Author
Randall Hand
URL
If you spend much time in a terminal, be it on Mac or Linux, one thing you wind up doing often is creating and decompressing tarballs.  Be they tgz, tbs, or just plain tar files, they’re the archive format of choice for folks working in *nix environments due to their universal support.  Most commonly, the only way to get any real status information is to turn on “verbose” mode which outputs each filename as it goes.  That’s not terribly useful for large archives.
 
If you install the ‘pv’ tool, you can partner it with some commandline-fu to get nice progress bars.  But why deal with it, when you can write a fish function to do it for you!
 
Here's a script (expand.fish) that decompresses a variety of formats:
 
    #expand
    function expand -d 'Decompress a file' -a filename
        set -l extension ( echo $filename | awk -F . '{print $NF}')
        switch $extension
            case tar
                echo "Un-tar-ing $filename..."
                pv $filename | tar xf -
            case tgz
                echo "Un-tar/gz-ing $filename..."
                pv $filename | tar zxf -
            case tbz
                echo "Un-tar/bz-ing $filename..."
                pv $filename | tar jxf -
            case gz
                echo "Un-gz-ing $filename..."
                pv $filename | gunzip -
            case bz
                echo "Un-bz-ing $filename..."
                pv $filename | bunzip2 -
            case zip
                echo "Un-zipping $filename..."
                unzip $filename
            case '*'
                echo I don\'t know what to do with $extension files.
        end
    end
 
And here's a matching script for creating tarballs:
 
    #tarball
    function tarball -d "Create a tarball of collected files" -a filename
        echo "Creating a tarball of $filename"
        if [ -e $filename ]
            echo "Sorry, $filename already exists."
            return
        end
        set -l args $argv[2..-1]
        set -l size (du -ck $args | tail -n 1 | cut -f 1)
        set -l extension ( echo $filename | awk -F . '{print $NF}')
 
        switch $extension
            case tgz
                tar cf - $args | pv -p -s {$size}k | gzip -c > $filename
            case tbz
                tar cf - $args | pv -p -s {$size}k | bzip2 -c > $filename
            case '*'
                echo "I don't know how to make a '$extension' file."
                return
        end
        set -l shrunk (du -sk $filename | cut -f 1)
        set -l ratio ( math "$shrunk * 100.0 / $size")
        echo Reduced {$size}k to {$shrunk}k \({$ratio}%\)
end
 
Enjoy!