Skip to content

Instantly share code, notes, and snippets.

@krscott
Last active January 24, 2023 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krscott/20c5e965950479a0b70608fa0fe75fe5 to your computer and use it in GitHub Desktop.
Save krscott/20c5e965950479a0b70608fa0fe75fe5 to your computer and use it in GitHub Desktop.
Bash script template
#!/usr/bin/env bash
# exit when any command fails
set -e
trap 'echo ''; echo Error at $(basename "$0"):${LINENO}: $BASH_COMMAND' ERR
# Get this script's directory
SDIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"
## Optional extras ##
# Change directory to this script's directory
cd "$SDIR"
# Support '**' glob\
shopt -s globstar
shopt -s nullglob
# Check for args
usage() {
echo "Usage: $(basename -- "$0") ARG"
exit 1
}
[[ -n "$1" ]] || usage
# Run Windows batch script
batch() {
local args="$@"
cmd.exe /c "$args"
}
timestamp()
{
date "+%Y%m%d-%H%M%S"
}
# Delete everything in `dist/`, but do nothing if empty
# find dist -path 'dist/*' -prune -exec rm -r -- {} +
# Get filename parts
file_ext()
{
filename=$(basename -- "$1")
echo "${filename##*.}"
}
basename_no_ext()
{
filename=$(basename -- "$1")
echo "${filename%.*}"
}
# Logger
log() {
echo "[$(date --rfc-3339=seconds)] $@" >> "$SDIR/log.txt"
echo "$@"
}
logerr() {
log "ERROR" "$@"
return 1
}
# Find 7z (Windows)
if ! type 7z 2> /dev/null && [ -e "/c/Program Files/7-Zip/7z.exe" ]; then
PATH="$PATH:/c/Program Files/7-Zip/"
fi
# 7z a -tzip archive.zip *
# Progress bar animation
draw_progress_bar() {
local value=$1
local max=$2
local msg=${3:-""}
local bar_width=${4:-50}
if [[ -z "$COLUMNS" ]]; then
COLUMNS="$(tput cols)"
fi
if [[ -z "$MSG_PADDING" ]]; then
MSG_PADDING=" "
fi
if [[ -n "$msg" ]]; then msg=" $msg"; fi
# Calculate percentage
if (( $max < 1 )); then max=1; fi # anti zero division protection
local percentage=$(( 100 - (max*100 - value*100) / max ))
# Rescale the bar according to the progress bar width
local num_bar=$(( percentage * bar_width / 100 ))
# Draw progress bar
local bar_str="["
for b in $(seq 1 $num_bar); do bar_str+="#"; done
for s in $(seq 1 $(( bar_width - num_bar ))); do bar_str+=" "; done
bar_str+="] $percentage%$msg$MSG_PADDING"
printf '%.*s\r' $((COLUMNS - 1)) "$bar_str"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment