Bash getopt - shift multiple parameters

2019-07-10 00:33发布

问题:

I have a script to launch some checks on Ubuntu machine.

I call my script like this : ./script -f /tmp/file.txt --modules 001 002 003

All files 001, 002, etc... are bash scripts.

The following main function is my problem :

main () {
OPTS=`getopt -o hf:m: --long help,file:,modules: -n 'script.sh' -- "$@"`

eval set -- "$OPTS"
    [ $# -eq 0 ] && echo "Unknown options or parameters" && USAGE

while [ $# -gt 0 ]; do
    case "$1" in
            -f|--file)
               FILE="$2"
               shift
               ;;
            -h|--help)
               USAGE
               exit 1
               ;;
            -m|--modules)
               MODULES="$2"
               shift
               ;;
    esac
    shift
done

[ -z "$MODULES" ] && echo "No module specified" && USAGE
}

I would that $MODULES variable contains for example 001 002 004.
I tried different things with shift, but that's some complicated..

Ideally, if I can use "$@" as the rest of the script settings , this could be great.

EDIT : With ./script.sh -f /tmp/file.txt --modules "001 002 003" finally the $MODULES variable contains "001 002 003" , for example.

But I have a for loop which seems to not iterate on all the args, only on the first... each $module contains "001 002 003".

for module in "$MODULES"; do 
    echo "Importing Module $module"
    . modules/$module >> "$FILE" 
done

回答1:

Getopt can't get an arbitrary numbers of values, but you can pass modules list as a parameter usign " and later parser it:

./script -f /tmp/file.txt --modules "001 002 003"

Inside your script you can get each individual value:

for module in $MODULES ; do  
   echo $module
done