Passing named arguments to shell scripts
If you don't mind being limited to single-letter argument names i.e. my_script -p '/some/path' -a5
, then in bash you could use the built-in getopts
, e.g.
#!/bin/bash
while getopts ":a:p:" opt; do
case $opt in
a) arg_1="$OPTARG"
;;
p) p_out="$OPTARG"
;;
\?) echo "Invalid option -$OPTARG" >&2
;;
esac
done
printf "Argument p_out is %s\n" "$p_out"
printf "Argument arg_1 is %s\n" "$arg_1"
Then you can do
$ ./my_script -p '/some/path' -a5
Argument p_out is /some/path
Argument arg_1 is 5
There is a helpful Small getopts tutorial or you can type help getopts
at the shell prompt.
I stole this from drupal.org, but you could do something like this:
while [ $# -gt 0 ]; do
case "$1" in
--p_out=*)
p_out="${1#*=}"
;;
--arg_1=*)
arg_1="${1#*=}"
;;
*)
printf "***************************\n"
printf "* Error: Invalid argument.*\n"
printf "***************************\n"
exit 1
esac
shift
done
The only caveat is that you have to use the syntax my_script --p_out=/some/path --arg_1=5
.
I use this script and works like a charm:
for ARGUMENT in "$@"
do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
VALUE=$(echo $ARGUMENT | cut -f2 -d=)
case "$KEY" in
STEPS) STEPS=${VALUE} ;;
REPOSITORY_NAME) REPOSITORY_NAME=${VALUE} ;;
*)
esac
done
echo "STEPS = $STEPS"
echo "REPOSITORY_NAME = $REPOSITORY_NAME"
Usage
bash my_scripts.sh STEPS="ABC" REPOSITORY_NAME="stackexchange"
Console result :
STEPS = ABC
REPOSITORY_NAME = stackexchange
STEPS and REPOSITORY_NAME are ready to use in the script.
It does not matter what order the arguments are in.