Parse flags with getopts

POSIX option parsing: -n takes a value, -v is a simple switch

while getopts "n:v" o; do case $o in n) ns=$OPTARG;; v) verbose=1;; esac; done

tool
bash12 commands
tags
bashci

More bash commands

  • timeout -k 5s 30s ./long_task.sh || echo "timed out: $?"

    Sends SIGTERM after 30s, then SIGKILL 5s later. Exit code 124 means the command timed out

  • exec 3>>audit.log; echo "$(date -Is) start" >&3; exec 3>&-

    Open fd 3 to a file, write to it separately from stdout, then close it

  • setopt extendedglob; print -l **/*(.); autoload zmv; zmv '(*).txt' '$1.bak'

    zsh: list only regular files recursively, then safely rename many files with zmv

  • set -euo pipefail; IFS=$'\n\t'

    Stop on errors, unset variables and failed pipes. Split words only on newline and tab

  • tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT INT TERM

    Remove the mktemp dir on exit or signal. Note: quote $tmp so paths with spaces work

all 12 bash commands