2

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
Isador
  • 595
  • 3
  • 10
  • 23
  • You need to figure out what't the difference between quoting a variable and leaving it unquoted. With `for mod in "$MODULES"`, you're only ever going to have a single loop iteration. With `for mod in "$MODULES"`, you're letting the shell perform [word splitting](https://www.gnu.org/software/bash/manual/bashref.html#Word-Splitting) (and [filename expansion](https://www.gnu.org/software/bash/manual/bashref.html#Filename-Expansion)!) on the variable's value, so you will have multiple iterations through the loop. [Be careful though](http://unix.stackexchange.com/q/171346/4667) – glenn jackman Jan 29 '16 at 11:41
  • I think I need to use a list (and not a variable) but I don't see how to create a list in my ̀case` loop. – Isador Jan 29 '16 at 17:33
  • You would do : `set -f; modules=($2); set +f` - - the set commands turn off/on filename expansion – glenn jackman Jan 29 '16 at 18:19
  • Thank you. Finally it was too my call to `for module in "${MODULES[*]}" ` . I needed to remove the `"` character. – Isador Feb 01 '16 at 14:12
  • No, don't do that: use `for module in "${MODULES[@]}"` -- keep the quotes but use `@` -- see http://stackoverflow.com/q/12314451/7552 – glenn jackman Feb 01 '16 at 14:20

1 Answers1

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
Joan Esteban
  • 1,006
  • 12
  • 23