Skip to content

Instantly share code, notes, and snippets.

@ConnerWill
Created December 19, 2025 20:42
Show Gist options
  • Select an option

  • Save ConnerWill/57ba973baebf8f67fefbb5a7cd8a47a0 to your computer and use it in GitHub Desktop.

Select an option

Save ConnerWill/57ba973baebf8f67fefbb5a7cd8a47a0 to your computer and use it in GitHub Desktop.
Yet another bash script template
set -Eeuo pipefail
# ---------- UI helpers ----------
RED=$'\e[31m'; GRN=$'\e[32m'; BLU=$'\e[34m'; YLW=$'\e[33m'; BLD=$'\e[1m'; CLR=$'\e[0m'
err() { printf "%s[ERROR]%s %s\n" "$RED" "$CLR" "$*" >&3; }
ok() { printf "%s[OK]%s %s\n" "$GRN" "$CLR" "$*" >&3; }
info() { printf "%s[INFO]%s %s\n" "$BLU" "$CLR" "$*" >&3; }
warn() { printf "%s[WARN]%s %s\n" "$YLW" "$CLR" "$*" >&3; }
require_root() { [[ $EUID -eq 0 ]] || { err "Please run as root (sudo)."; exit 1; }; }
# ---------- Percentage bar ----------
STEP_NUM=0; STEP_MAX=0; BAR_WIDTH=44
repeat_char(){ local n=${1:-0} c="${2:-#}"; (( n<=0 )) && { printf ""; return; }; perl -e 'print $ARGV[1] x $ARGV[0]' "$n" "$c"; }
draw_bar(){ local pct=${1:-0}; (( pct<0 ))&&pct=0; (( pct>100 ))&&pct=100; local f=$(( pct * BAR_WIDTH / 100 )); printf "\r[%-*s] %3d%%" "$BAR_WIDTH" "$(repeat_char "$f" "#")" "$pct" >&3; }
advance_bar(){ STEP_NUM=$((STEP_NUM+1)); (( STEP_MAX < 1 )) && STEP_MAX=1; local pct=$(( STEP_NUM * 100 / STEP_MAX )); draw_bar "$pct"; }
cleanup_on_error(){ printf "\n" >&3; err "An unexpected error occurred. See the log: $LOGFILE"; }
trap cleanup_on_error ERR
LOGFILE="$(pwd)/log-$(date +%Y%m%d-%H%M%S).log"
exec 3>&1
exec > >(tee -a "$LOGFILE") 2>&1
require_root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment