Skip to content

Instantly share code, notes, and snippets.

@robotamer
Forked from jacius/untar
Created February 24, 2023 19:13
Show Gist options
  • Save robotamer/5876cdff0e6f1cc85cefdcd43ca49e7e to your computer and use it in GitHub Desktop.
Save robotamer/5876cdff0e6f1cc85cefdcd43ca49e7e to your computer and use it in GitHub Desktop.
untar: A simple shell script to untar a tarball.
#!/bin/bash
#
# A simple command to untar any tarball.
#
# For times when you don't care whether it was compressed
# with bzip2 or gzip, you just want to untar it already!
#
# Usage: untar [-v|--verbose] file
#
# Author: John Croisant
#
# License: Do whatever you want.
#
# History:
# 2009-10-05: Initial version. (JC)
# 2009-10-06: Added -v/--verbose flag. (JC)
# Improved file type detection, w/ support for symlinks. (JC)
# 2011-05-13: Added -l/-t/--list and -x/--extract flags. (JC)
# Added detection for .tar.xz files.
#
script=$(basename $0)
opts=`getopt -n "$script" -o "vltx" -l "verbose" -l "list" -l "extract" -- "$@"`
if [ ! $? -eq 0 ]; then exit 1; fi # getopt failed
# Overwrite the script's positional parameters with getopt's output:
set -- $opts
verbose=false
action=extract
while [ $# -gt 0 ]; do
case "$1" in
-v | --verbose)
verbose=true;;
-l | -t | --list)
action=list;;
-x | --extract)
action=extract;;
--)
shift; break;;
*)
break;
esac
shift
done
function file_type {
if [ ! -e $1 ]; then
echo "missing"; return 1;
fi
case $(file --brief --dereference --mime --uncompress $1) in
application/x-tar*application/x-gzip*)
echo "tar.gz";;
application/x-tar*application/x-bzip2*)
echo "tar.bz2";;
application/x-tar*application/x-xz*)
echo "tar.xz";;
application/x-tar*)
echo "tar";;
*)
echo "unknown"; return 1;;
esac
}
function handle_file {
target=`eval echo $1` # strip 'quotes' that getopt made
tarflags=
if [ true = $verbose ]; then
tarflags="-v $flags"
fi
case $action in
extract)
tarflags="$tarflags -x";;
list)
tarflags="$tarflags -t";;
esac
case $(file_type $target) in
*) ;;
missing)
echo "$script: $target: No such file"
return 1;;
tar.gz)
tarflags="$tarflags -z";;
tar.bz2)
tarflags="$tarflags -j";;
tar.xz)
tarflags="$tarflags -J";;
tar)
;;
*)
echo "$script: $target: That's not a tarball, silly"
return 1;;
esac
tar $tarflags -f $target;
}
handle_file $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment