bashgetopt

Why can't assign value with getopt?


Here is my test.sh:

#!/usr/bin/env bash
arg="default"
TEMP=$(getopt --long been: -n 'test.sh' -- "$@")
eval set -- "$TEMP"
while true ; do
    case "$1" in
        --been)
            echo 'in been option'
            arg="$2"
            shift;;
        --)
            echo 'in the end' 
            shift ; break ;;
    esac
done
echo "$arg"

Assign value to the arg:

bash  ./test.sh  --been=xxyyzz
in the end
default

Why can't get the result>?

bash  ./test.sh  --been=xxxx
in been option
xxxx

Solution

  • The getopt(1) manpage mentions, way down in the BUGS section,

    The syntax if you do not want any short option variables at all is not very intuitive (you have to set them explicitly to the empty string).

    So you need

    getopt --long been: -n test.sh "" "$@"
    

    (If you want to include the -- in the getopt arguments, it needs to come before that empty argument)

    With that change,

    in been option
    xxyyzz
    

    (You also need a break in the --been case section, and to use shift 2 to get rid of the argument)