Skip to content

Instantly share code, notes, and snippets.

@wasertech
Created July 20, 2022 15:01
Show Gist options
  • Save wasertech/abf49b3fe6a5a17ff82d767c83abf568 to your computer and use it in GitHub Desktop.
Save wasertech/abf49b3fe6a5a17ff82d767c83abf568 to your computer and use it in GitHub Desktop.
Zsh function to extract common file formats
### Function extract for common file formats ###
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
function extract {
if [ -z "$1" ]; then
# display usage if no parameters given
echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>"
echo " extract <path/file_name_1.ext> [path/file_name_2.ext] [path/file_name_3.ext]"
else
for n in "$@"
do
if [ -f "$n" ] ; then
case "${n%,}" in
*.cbt|*.tar.bz2|*.tar.gz|*.tar.xz|*.tbz2|*.tgz|*.txz|*.tar)
tar xvf "$n" ;;
*.lzma) unlzma ./"$n" ;;
*.bz2) bunzip2 ./"$n" ;;
*.cbr|*.rar) unrar x -ad ./"$n" ;;
*.gz) gunzip ./"$n" ;;
*.cbz|*.epub|*.zip) unzip ./"$n" ;;
*.z) uncompress ./"$n" ;;
*.7z|*.arj|*.cab|*.cb7|*.chm|*.deb|*.dmg|*.iso|*.lzh|*.msi|*.pkg|*.rpm|*.udf|*.wim|*.xar)
7z x ./"$n" ;;
*.xz) unxz ./"$n" ;;
*.exe) cabextract ./"$n" ;;
*.cpio) cpio -id < ./"$n" ;;
*.cba|*.ace) unace x ./"$n" ;;
*)
echo "extract: '$n' - unknown archive method"
return 1
;;
esac
else
print_center_with_banner "'$n' - file does not exist"
return 1
fi
done
fi
}
IFS=$SAVEIFS
@wasertech
Copy link
Author

wasertech commented Jul 20, 2022

It's written for zsh but should work with bash too.

You need the following tools to use (fully):

  • tar
  • unlzma
  • bunzip2
  • unrar
  • gunzip
  • unzip
  • uncompress
  • 7z
  • unxz
  • cabextract
  • cpio
  • unace

Example:

❯ extract
Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>
       extract <path/file_name_1.ext> [path/file_name_2.ext] [path/file_name_3.ext]

❯ extract  archive.zip
Archive:  ./archive.zip
   creating: archive/
  inflating: archive/file1.md  
  inflating: archive/file2.json
  inflating: archive/file3.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment