Last active
August 27, 2024 21:32
-
-
Save cartercanedy/c488b4734e8b0b1808690362075c285c to your computer and use it in GitHub Desktop.
A shell command to get a progress bar while creating a tarball
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
#!/usr/bin/env bash | |
function error() { | |
# $1 err code | |
# $2 err msg | |
echo -e "error: $1: $2" | |
} | |
function tgz() { | |
local longopts="help,output:,force" | |
local opts="ho:f" | |
local usage=" | |
tgz -o|--output <OUTPUT_PATH> [ -f|--force ] FILE [ ... ] | |
Create an archive with name OUTPUT_PATH containing FILE... | |
tgz -h|--help | |
Print this help dialog and exit | |
ARGS: | |
--output | -o path to where the file should be written, must not be a directory | |
--force | -f overwrite any file that exists at OUTPUT_PATH | |
FILES file path or glob pattern for capturing input files | |
USAGE: | |
tgz --output ./archive.tar.gz file-1.txt file-2.txt # captures only file-1.txt & file-2.txt and writes the archive to | |
# ./archive.tar.gz, failing if a file already exists | |
tgz -fo ./archive.tgz file-?.txt # captures files matching pattern file-?.txt (file-1.txt, | |
# file-2.txt, file-3.txt, etc.) and writes the archive to | |
# ./archive.tgz, overwriting the file if it already exists | |
" | |
parsed=$(getopt --options "$opts" --longoptions "$longopts" --name "tgz" -- "$@") | |
if [ $? -ne "0" ]; then | |
echo -e "$usage" | |
exit 1 | |
fi | |
eval set -- "$parsed" | |
local files="" | |
local output="" | |
local force="n" | |
while true; do | |
case $1 in | |
-h|--help) | |
echo "$usage" | |
return 0 | |
;; | |
-o|--output) | |
output=$2 | |
shift 2 | |
;; | |
-f|--force) | |
force="y" | |
shift | |
;; | |
--) | |
shift | |
files=$@ | |
break | |
;; | |
esac | |
done | |
if [ -d "$output" ]; then | |
error 2 "can't overwrite a directory" | |
return 2 | |
elif [ -f "$output" ] && ! [ "$force" == "y" ]; then | |
error 3 "can't overwrite a file that already exists, use -f|--force to ignore files that already exist" | |
return 3 | |
elif [ "$files" == "" ]; then | |
error 4 "need some files to archive" | |
return 4 | |
else | |
for file in $files; do | |
if ! [ -f "$file" ]; then | |
error 5 "file \"$file\" doesn't exist" | |
return 5 | |
fi | |
done | |
fi | |
tar -zcO $files | pv -s $(du -sb $files | awk '{sum+=$1;} END{print sum}') | gzip > "$output" | |
return 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment