Bash getopt - shift multiple parameters

ε祈祈猫儿з 提交于 2019-12-11 02:13:36

问题


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


来源:https://stackoverflow.com/questions/35081838/bash-getopt-shift-multiple-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!