I have a bash script (script.sh
) that takes in many parameters in the format --keyword value
. It is read in when the script is invoked with the following lines:
# Get our arguments using flags,
while [[ "$#" > 1 ]]; do
case "$1" in
"--h")
help
exit
;;
"--param1") param1="$2"; shift 2;;
"--param2") param2="$2"; shift 2;;
"--param3") param3="$2"; shift 2;;
esac
done
Suppose I want to introduce a --param4
that takes in one or many parameters instead of just one. e.g.
bash ./script.sh --param1 a --param2 b --param3 c --param4 x y z
The order shouldn't matter theoretically matter, so after hitting param4, we should keep pulling in the next parameters until we hit another --param flag.
How can I actually parse this list? The end goal is to iterate through param4 as feed it as a parameter to a Python script. (something like):
for item in $param4; do
python my_python_script.py --${item}
done
Try this:
usage(){ echo 'usage: ...'; exit 2; }
while [ "$#" -gt 1 ]; do
case $1 in
--param1) param1=$2; shift 2;;
--param2) param2=$2; shift 2;;
--param3) param3=$2; shift 2;;
--param4)
shift
while [ "$#" -gt 0 ]; do
case $1 in
--param*) break;;
*) param4+=("$1"); shift;;
esac
done
;;
*) usage ;;
esac
done
[ "$#" -gt 0 ] && usage
for p in "${param4[@]}"; do
echo python "--$p"
done