Pass parameters as option in custom getopts script in bash

2.3k views Asked by At

I'd like to pass options as a parameter. E.g.:

mycommand -a 1 -t '-q -w 111'

The script cannot recognize a string in quotes. I.e it gets only part of the string.

getopts works the same - it see only -q.

For custom getopts I use similar script (example):

while :
do
    case $1 in
        -h | --help | -\?)
            # Show some help
            ;;
        -p | --project)
            PROJECT="$2"
            shift 2
            ;;
        -*)
            printf >&2 'WARN: Unknown option (ignored): %s\n' "$1"
            shift
            ;;
        *)  # no more options. Stop while loop
            break
            ;;
        --) # End of all options
        echo "End of all options"
            shift
            break
            ;;
    esac
done
1

There are 1 answers

2
cdarke On BEST ANSWER

Maybe I misunderstand the question, but getopts seems to work for me:

while getopts a:t: arg
do
    case $arg in
        a)  echo "option a, argument <$OPTARG>"
            ;;
        t)  echo "option t, argument <$OPTARG>"
            ;;
    esac
done

Run:

bash gash.sh -a 1 -t '-q -w 111'
option a, argument <1>
option t, argument <-q -w 111>

Isn't that what you want? Maybe you missed the : after the options with arguments?