Created
December 25, 2020 14:30
-
-
Save yoogottamk/02a3db8d601a5147277bcee39b235405 to your computer and use it in GitHub Desktop.
Extracts through multiple layers of different types of compression.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Extracts a file (through multiple layers) and prints it's contents | |
# Usage: $0 <filename> | |
# Options: | |
# - [ENV] EXTRACT_DEBUG: Prints each step if variable is set | |
[[ $# -eq 0 ]] && { >&2 echo "Usage: $0 filename"; exit 1; } | |
# returns mimetype | |
# ignores tests for csv/json, etc files | |
function getmime { | |
file -bi -e{compress,csv,json} "$1" | cut -d';' -f1 | |
} | |
filename="$1" | |
# ext/tool map | |
declare -A extract | |
extract[application/x-tar]="tar xO" | |
extract[application/gzip]=gunzip | |
extract[application/x-xz]=unxz | |
extract[application/zip]=gunzip | |
extract[application/x-bzip2]=bunzip2 | |
while :; do | |
filemime="$( getmime "$filename" )" | |
new_name="$( mktemp -p . )" | |
[[ ! -z $EXTRACT_DEBUG ]] && { >&2 echo "Got mime $filemime; extracting $filename to $new_name"; } | |
[[ "$filemime" =~ "text/*" ]] && { cat "$filename"; exit 0; } | |
if [[ ! -z ${extract["$filemime"]} ]]; then | |
${extract["$filemime"]} < "$filename" > "$new_name" | |
rm "$filename" | |
filename="$new_name" | |
else | |
>&2 echo Unknown filetype "$filemime" | |
exit 1 | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment