There are so many applications available to extract various types of archive files. Remembering all options and parameters of each archive tool would be difficult for you. No worries! Today, I came across a simple Bash function to extract file archives of various types in Linux.
This Bash function can able to extract most commonly used archive formats, such as .tar.bz2, .tar.bz, .bz2, .rar, .zip, and .7z etc. You don’t need to use the actual archiving application to extract an archive file! Just add this function to your ~/bashrc
file and call it to extract the archive files. It will automatically find and use the appropriate archiving tool to extract the files. No need to memorize the flags and options!
Bash Function To Extract File Archives Of Various Types
Open your ~/.bashrc
file:
$ nano ~/.bashrc
Add the following snippet at the end:
# Bash Function To Extract File Archives Of Various Types
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 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted via extract()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
Press Ctrl+o
and press ENTER to save the file and then press Ctrl+
x to exit the file. Run the following command to take effect the changes:
$ source ~/.bashrc
From now on, you can simply call this function to extract various types of archive files.
For example, I am going to extract a .7z
archive file type using command:
$ extract archive.7z
Sample output:
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_IN,Utf16=on,HugeFiles=on,64 bits,4 CPUs Intel(R) Core(TM) i3-2350M CPU @ 2.30GHz (206A7),ASM)
Scanning the drive for archives:
1 file, 16013693 bytes (16 MiB)
Extracting archive: archive.7z
--
Path = archive.7z
Type = 7z
Physical Size = 16013693
Headers Size = 1204
Method = LZMA:23
Solid = +
Blocks = 1
Everything is Ok
Folders: 21
Files: 37
Size: 16625007
Compressed: 16013693
Similarly, to extract .zip
type files, the command would be:
$ extract archive.zip
Please note that you must have installed the appropriate archive manager before using this function. If there are no supported archive tools installed on your system, you will receive an error message like below:
$ extract archive.zip
bash: /usr/bin/unzip: No such file or directory
The original author of this script is unknown. This script is mentioned in multiple places on the Internet. If anyone know who wrote this, please let me know in the comment section below. I will add the author’s details.
Are you using any other cool Bash functions? Please share them via the comment section. It could be useful for me and as well as all readers.
Related read: