Shell¶
Daniel Weschke
January 1, 2019
1 Check if programs are callable¶
is_callable(){
for cmd in "$@"; do
command -v "$cmd" >/dev/null 2>&1 || return 1
done
}
2 Exit with error messages¶
error_exit(){
for estr in "${@:2}"; do
echo "$estr" >&2
done
exit "$1"
}
3 Script with options and arguments¶
#!/bin/sh
docstring="Usage: ${0##*/} [OPTION]... PATTERN [PATH]...
Search for the PATTERN inside files.
Arguments:
PATTERN the string pattern to search for
PATH the file or directory
Options:
-f FILE, --file=FILE input file
-v, --verbose print additional messages
-h, --help show this help message and exit
-V, --version show version and exit"
versionstring="${0##*/} version 2019.01.01 © 2019 Daniel Weschke"
fflag=
vflag=
debug=
while getopts :f:vhV-:D opt; do
case $opt in
f) fflag=1;;
fval="$OPTARG";;
v) vflag=1;;
h) echo "$docstring"; exit 0;;
V) echo "$versionstring"; exit 0;;
-) LONG_OPTARG="${OPTARG#*=}"
case $OPTARG in
file=?*) fflag=1
fval="$LONG_OPTARG";;
file*) echo "No arg for --$OPTARG option" >&2; exit 2 ;;
verbose) vflag=1;;
help) echo "$docstring"; exit 0;;
version) echo "$versionstring"; exit 0;;
verbose=*|help=*|version=*)
echo "No arg allowed for --${OPTARG//=*} option" >&2; exit 2 ;;
'' ) break ;; # "--" terminates argument processing
* ) echo "Illegal option --$OPTARG" >&2; exit 2 ;;
esac ;;
D) debug=1;;
\?) echo "Invalid option: -$OPTARG" >&2; exit 2;; # without leading : getopts already reported the illegal option
:) echo "Option -$OPTARG requires an argument." >&2; exit 2;;
esac
done
shift "$((OPTIND-1))" # shift to additional command line arguments, accessible with $1, ...
# (remove parsed options from $@ list)
if (($# == 0)); then
echo "Error: No pattern entered" >&2
exit 2
fi