Automatically choose the right extraction method for a compressed file

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;;*.7z) 7z x $1;;esac fi}
The function had to be cut down to meet the maximum command length requirements. The full version of the function is: 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 } Note: This is not my original code. I came across it in a forum somewhere a while ago, and it's been such a useful addition to my .bashrc file, that I thought it worth sharing.
Sample Output
$ extract foo_bar.tar.gz

0
By: SamuelWN
2016-02-08 14:52:05

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: