Skip to content

Instantly share code, notes, and snippets.

@brandonhimpfen
Created January 24, 2026 19:56
Show Gist options
  • Select an option

  • Save brandonhimpfen/696f180b1b990d2b175195a54b8575a9 to your computer and use it in GitHub Desktop.

Select an option

Save brandonhimpfen/696f180b1b990d2b175195a54b8575a9 to your computer and use it in GitHub Desktop.
Bash extract() helper to extract most archive formats (.zip, .tar.gz, .7z, .rar, etc.) with safe checks and readable errors.
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Extract any archive (zip, tar.gz, tgz, tar.bz2, tar.xz, 7z, rar, etc.)
# -----------------------------------------------------------------------------
# Usage:
# ./bash-extract-archive.sh file.tar.gz
# source this file and call: extract "file.zip"
#
# Requirements (depending on format):
# - tar, unzip, gzip/bzip2/xz, 7z, unrar, cabextract
# -----------------------------------------------------------------------------
set -Eeuo pipefail
error() {
printf 'ERROR: %s\n' "$*" >&2
}
usage() {
cat <<EOF
Usage: $(basename "$0") <archive>
Example:
$(basename "$0") file.tar.gz
EOF
}
extract() {
local file="${1:-}"
if [[ -z "$file" ]]; then
error "No file provided"
return 2
fi
if [[ ! -f "$file" ]]; then
error "File not found: $file"
return 2
fi
case "$file" in
*.tar)
tar -xf "$file"
;;
*.tar.gz|*.tgz)
tar -xzf "$file"
;;
*.tar.bz2|*.tbz2)
tar -xjf "$file"
;;
*.tar.xz|*.txz)
tar -xJf "$file"
;;
*.tar.zst)
# Requires GNU tar with zstd support, OR: unzstd then tar -xf
tar --use-compress-program=unzstd -xf "$file"
;;
*.zip)
unzip -q "$file"
;;
*.gz)
gunzip -k "$file"
;;
*.bz2)
bunzip2 -k "$file"
;;
*.xz)
unxz -k "$file"
;;
*.zst)
unzstd -k "$file"
;;
*.7z)
7z x -y "$file" >/dev/null
;;
*.rar)
unrar x -y "$file" >/dev/null
;;
*.cab)
cabextract "$file" >/dev/null
;;
*)
error "Unsupported archive format: $file"
return 3
;;
esac
}
main() {
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" || $# -ne 1 ]]; then
usage
exit 0
fi
extract "$1"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment