There are large number of archive file formats – .zip, .tar.gz, .tar, .gz, .7zip, .rar, etc etc..
I find it difficult to remember the command line options for extracting different archive file formats. So, I wrote a bash function which given a archive filename as an input extracts it.
Here’s the function :
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) rar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.z) uncompress $1 ;;
*) echo "'$1' cannot be extracted via extract ()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
This function is pretty self explanatory. But as it is not powerful. It becomes the ultimate tool for extractive archive files if you copy this function in you bashrc file (~/.bashrc).
Now you can simply extract any file like this:
$extract test.tar.gz
Hope you like this function.
Note: This function doesn’t work with files have space in its name. I didn’t waste time in solving this issue as I normally don’t use such filenames. If any of you solve this issue, please do let me know. I would include it with your name in this post.
Pingback: You are now listed on FAQPAL
Wow, thanks for compiling and sharing.
I made the changes for the script to work for file names with spaces , i tired its working fine here , hope its bugs free.
#!/bin/bash
extract()
{
SAVEIFS=$IFS
IFS=$(echo -en “\n\b”)
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) rar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.z) uncompress $1 ;;
*) echo “‘$1? cannot be extracted via extract ()”;;
esac
else
echo “‘$1? is not a valid file”
fi
IFS=$SAVEIFS
}
Also google for “unball” script. Provides similar functionality as long as you have the proper decompression program installed.
>> This function doesn’t work with files have space in its name
The solution is very simple: just put double-quotes around every appearance of “$1″, e.g.
if [ -f "$1" ] ; then
case “$1″ in
*.tar.bz2) tar xjf “$1″ ;;
… and so on
@Marc
Thanks for your hint.
I will update the blog accordingly.