dotfiles/bin/extract

57 lines
1.6 KiB
Plaintext
Raw Normal View History

2020-03-26 18:52:38 +00:00
#!/usr/bin/env sh
# Extracts the archive.
# The process can vary depending on the file extension.
# Usage: $0 ARCHIVE_FILE
# Dependencies:
# * xxd V1.10 27oct98 by Juergen Weigert
# * UnZip 6.00 of 20 April 2009
# * tar (GNU tar) 1.32
# * printf (GNU coreutils 8.31)
function get_bytes() {
local file=$1
local length=${2:-20}
# Getting the file signature.
# At most, we will just get the first 20 bytes of the file.
local file_sig=$(xxd -l "$length" -ps "$file")
printf "$file_sig"
}
function extract_path_without_ext() {
local path=$1
local filename=$(basename -- "$path")
# Return the filename without the file extension.
# For more information, you can look up the parameter expansion in
# https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html.
# Even if the filename has no extension, it will print the whole filename.
printf "${filename%.*}"
}
function extract_file() {
local file=$1
local length=$2
# Checking the file signatures.
# The reference is at https://en.wikipedia.org/wiki/List_of_file_signatures.
local file_sig=$(get_bytes "$file" "$length")
# Extracting the extension out of the given file and creating a directory out of it.
local file_without_ext=$(extract_path_without_ext "$file")
mkdir -p "$file_without_ext"
# Checking if the file signature matches of a zip
if [[ $(printf "$file_sig" | head -c 4) == "504b" ]]; then
cd "$file_without_ext" && unzip "../$file"
else
tar xf "$file" --directory "$file_without_ext"
fi
}
extract_file $1