I am using this code to parse the first argument passed to my script. It error handles and it works just the way I want it:
if [ -z "$action" ]; then
printf "[${c_RED}ERROR${c_RESET}] The action must be specified.\n" && exit 1
elif [[ "$action" =~ ^-{0,2}[Hh][Ee][Ll][Pp]$ ]] || [[ "$action" =~ ^-{0,2}[Hh]$ ]]; then
printf "Usage: pocsag [ACTION] [INPUTMETHOD/REDACTION] [OUTPUTMETHOD/PATHTOFILE/SERVICEACTION] "
printf "Examples: "
printf " pocsag decode rtlsdr cli "
printf " pocsag decode netcat file "
printf " pocsag redact medical ~/media/signals/pocsag/decoded/POCSAG* "
printf " pocsag service rtlsdr start "
printf " "
printf "Actions: "
printf " decode Envoke the usage of the input tuner, sox and multimon-ng to decode the signals. "
printf " redact Copy file but redact regex matching lines of a file. For example: Removing medical TXs. "
printf " service Used to start/stop the systemd service in user's ~/.config. Relies on rtlsdr_pager_rx "
printf " "
printf "Input Methods: "
printf " rtlsdr Use an RTLSDR device plugged into the local computer. "
printf " netcat Listen to localhost:7355 using netcat, then process and output locally. "
printf " "
elif ! [[ "$action" =~ ^([Dd][Ee][Cc][Oo][Dd][Ee]|[Rr][Ee][Dd][Aa][Cc][Tt]|[Ss][Ee][Rr][Vv][Ii][Cc][Ee])$ ]]; then
printf "[${c_RED}ERROR${c_RESET}] The action must be 'decode', 'redact' or 'service'.\n" && exit 3
fi
I now want to make this script POSIX compliant and cannot use the [[ ]] bash idiom. How would I go about this? Elaborate case statements? Surely there is a better method.
Thanks :)
^-{0,2}[Hh][Ee][Ll][Pp]$is a bit unnecessarily elaborate. Most tools are happy to just accept one version of a command line arg, or-hand--helpand that's it. Long options are usually all lowercase, but for short options the letter case usually matters:-hand-Hare different. And usually-helpis the same as-h -e -l -p(unless one of them takes an argument). Especially in the case of a "help" option, you could just recognize one form and print the help text anyway for the cases where the user gives an invalid option, e.g. the first branch here.if [ "$action" = "decode" ]; then ...; elif [ "$action" = "redact" ]; then ... else print_usage; fiorcase $action in action) ... redact) ... *) print_usage;; esac[[ ... =~ ... ]]is enough of a special case to be worth calling out. Most of[[can be substituted for with justtestwith careful quoting.