Bash: Tools – code examples
Options with getopts
Tools#getopts#cli#options
Use case: Build your own command-line tools with flags like -v and -o file.
#!/usr/bin/env bash
verbose=0; ausgabe="out.txt"
while getopts "vo:h" opt; do
case "$opt" in
v) verbose=1 ;;
o) ausgabe="$OPTARG" ;;
h) echo "Usage: $0 [-v] [-o file] name..."; exit 0 ;;
*) exit 2 ;;
esac
done
shift $((OPTIND - 1))
(( verbose )) && echo "verbose; output to $ausgabe"
echo "Remaining arguments: $*"getopts "vo:h" allows -v, -o value and -h. The value is in $OPTARG. After the loop, shift removes the options so that $@ contains only the remaining arguments.
Check Dependencies
Tools#command -v#dependencies#check
Use case: At the start of a script, make sure the required programs are installed.
benoetigt=(git curl jq)
for programm in "${benoetigt[@]}"; do
if ! command -v "$programm" > /dev/null 2>&1; then
echo "Missing: $programm" >&2
fehlt=1
fi
done
[[ -z "${fehlt:-}" ]] || exit 1
echo "All programs present"command -v portably checks whether a program is in the PATH (better than which). All missing programs are reported together, then the script aborts.
Confirmation Before Dangerous Actions
Tools#read#case#confirm
Use case: Interactive scripts that ask for confirmation before deleting or overwriting.
read -r -p "Really delete all .tmp files? [y/N] " antwort
case "$antwort" in
y|Y|yes|Yes) find . -name "*.tmp" -type f -print -delete ;;
*) echo "Cancelled." ;;
esacread -p shows a question; the default case (*) leads to an abort – so the safe variant stays the default. -print additionally prints what is being deleted.