> **CAVEAT**
> The solution below does not check for incomplete / malformed command invocation! For example, if `--p_out` requires an argument, but the command is called as `my-script.sh --p_out --arg_1 27` then it will happily assign the string `"--arg_1"` to the `p_out` variable.
This answer was initially an edit of [@cdmo's answer][1] (thanks to @Milkncookiez's comment also!), that got rejected as expected.
When using the variables, one can make sure that they have a default value set by using `"${p_out:-"default value"}"` for example.
From [3.5.3 Shell Parameter Expansion][2] of the GNU Bash manual:
> **`${parameter:-word}`**
> If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
#!/usr/bin/env bash
while [ $# -gt 0 ]; do
case "$1" in
-p|-p_out|--p_out)
p_out="$2"
;;
-a|-arg_1|--arg_1)
arg_1="$2"
;;
*)
printf "***************************\n"
printf "* Error: Invalid argument.*\n"
printf "***************************\n"
exit 1
esac
shift
shift
done
# Example of using the saved command line arguments.
# WARNING: Any of these may be an empty string, if the corresponding
# option was not supplied on the command line!
echo "Without default values:"
echo "p_out: ${p_out}"
echo "arg_1: ${arg_1}"; echo
# Example of using parsed command line arguments with DEFAULT VALUES.
# (E.g., to avoid later commands being blown up by "empty" variables.)
echo "With default values:"
echo "p_out: ${p_out:-\"27\"}"
echo "arg_1: ${arg_1:-\"smarties cereal\"}"
If the above script is saved into `my-script.sh`, then these invocations are all equivalent:
$ . my-script.sh -a "lofa" -p "miez"
$ . my-script.sh -arg_1 "lofa" --p_out "miez"
$ . my-script.sh --arg_1 "lofa" -p "miez"
(where `.` is Bash's [`source`][3] command.)
To demonstrate the default values part, here's the output without any arguments given:
$ . my-script.sh
Without default values:
p_out:
arg_1:
With default values:
p_out: "27"
arg_1: "smarties cereal"
[1]: https://unix.stackexchange.com/a/204927/85131
[2]: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#index-parameter-expansion
[3]: https://ss64.com/bash/source.html