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 (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 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
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"
P_OUT='/some/path' ARG_1=5 my_script
works with no extra steps. You can reference the env vars directly in the script, with defaults, error handling for missing values etc. I'm trying to imagine why the extra effort for command-line params is worthwhile.