# Copyright 2021 Chris Watson (watzon) # # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Most of this is taken verbatim from the oh-my-zsh "extract" plugin, just with a few changes. # Please see: https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/extract # ~/.local/bin/extract.zsh extract() { setopt localoptions noautopushd if (( $# == 0 )); then cat >&2 <<'EOF' Usage: extract [-option] [file ...] Options: -r, --remove Remove archive after unpacking. EOF fi local remove_archive=1 if [[ "$1" == "-r" ]] || [[ "$1" == "--remove" ]]; then remove_archive=0 shift fi local pwd="$PWD" while (( $# > 0 )); do if [[ ! -f "$1" ]]; then echo "extract: '$1' is not a valid file" >&2 shift continue fi local success=0 local extract_dir="${1:a:r}" local file="$1" full_path="${1:A}" case "${file:l}" in (*.tar.gz|*.tgz) (( $+commands[pigz] )) && { pigz -dc "$file" | tar xv } || tar zxvf --overwrite "$file" ;; (*.tar.bz2|*.tbz|*.tbz2) tar xvjf --overwrite "$file" ;; (*.tar.xz|*.txz) tar --xz --help &> /dev/null \ && tar --xz -xvf --overwrite "$file" \ || xzcat "$file" | tar xvf --overwrite - ;; (*.tar.zma|*.tlz) tar --lzma --help &> /dev/null \ && tar --lzma -xvf --overwrite "$file" \ || lzcat "$file" | tar xvf --overwrite - ;; (*.tar.zst|*.tzst) tar --zstd --help &> /dev/null \ && tar --zstd -xvf --overwrite "$file" \ || zstdcat "$file" | tar xvf --overwrite - ;; (*.tar) tar xvf --overwrite "$file" ;; (*.tar.lz) (( $+commands[lzip] )) && tar xvf --overwrite "$file" ;; (*.tar.lz4) lz4 -c -f -d "$file" | tar xvf --overwrite - ;; (*.tar.lrz) (( $+commands[lrzuntar] )) && lrzuntar -f "$file" ;; (*.gz) (( $+commands[pigz] )) && pigz -dk "$file" || gunzip -f -k "$file" ;; (*.bz2) bunzip2 -f "$file" ;; (*.xz) unxz -f "$file" ;; (*.lrz) (( $+commands[lrunzip] )) && lrunzip -f "$file" ;; (*.lz4) lz4 -f -d "$file" ;; (*.lzma) unlzma -f "$file" ;; (*.z) uncompress -f "$file" ;; (*.zip|*.war|*.jar|*.ear|*.sublime-package|*.ipa|*.ipsw|*.xpi|*.apk|*.aar|*.whl) unzip -o "$file" -d "$extract_dir" ;; (*.rar) unrar x -o+ -ad "$file" ;; (*.rpm) command mkdir -p "$extract_dir" && builtin cd -q "$extract_dir" \ && rpm2cpio "$full_path" | cpio --quiet -id ;; (*.7z) 7za x -aoa "$file" ;; (*.deb) command mkdir -p "$extract_dir/control" "$extract_dir/data" builtin cd -q "$extract_dir"; ar vx "$full_path" > /dev/null builtin cd -q control; extract ../control.tar.* builtin cd -q ../data; extract ../data.tar.* builtin cd -q ..; command rm *.tar.* debian-binary ;; (*.zst) unzstd -f "$file" ;; (*.cab) cabextract -d "$extract_dir" "$file" ;; (*.cpio) cpio -idmvF "$file" ;; (*) echo "extract: '$file' cannot be extracted" >&2 success=1 ;; esac (( success = success > 0 ? success : $? )) (( success == 0 && remove_archive == 0 )) && rm "$full_path" shift # Go back to original working directory in case we ran cd previously builtin cd -q "$pwd" done } extract $1 xdg-open ${1:a:r}