Extracting Any Compressed File from Terminal

Here’s how to extract any compressed file from the Bash command line terminal.

💬 If you prefer not to add this function to your bash environment you can just look for the command to use for the specific file type and enter it directly on the terminal command line. To do so, look at the suffix of your file, then find the *. with your suffix to look up the command you need.

For example, if I had a template.zip file I would fild the *.zip) unzip $file ;; line and can then infer that the command to extract a .zip file is unzip template.zip.

ex () { 
    local file="$1";
    [[ -z "$file" ]] && echo "usage: ex COMPRESSEDFILE" && return 1;
    [[ ! -f "$file" ]] && echo "'$file' is not a valid file" && return 1;
    case $file in 
        *.tar.bz2) tar xjf $file ;;
        *.tar.gz) tar xzf $file ;;
        *.bz2) bunzip2 $file ;;
        *.rar) unrar x $file ;;
        *.gz) gunzip $file ;;
        *.tar) tar xf $file ;;
        *.tbz2) tar xjf $file ;;
        *.tgz) tar xzf $file ;;
        *.zip) unzip $file ;;
        *.Z) uncompress $file ;;
        *.7z) 7z x $file ;;
        *.xz) unxz $file ;;
        *)
            echo "'$file' unknown compression suffix";
            return 1 ;;
    esac
}