1

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
2
  • Comma-separated list
    – roaima
    Sep 6 '19 at 21:27
  • Do not make a habit of using [[ > ]] instead of [[ -gt ]]: check [[ 2 > 10 ]] && echo yes to see why.
    – mosvy
    Sep 7 '19 at 3:21
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.