Search code examples
bashshellgetoptgetoptsgetopt-long

How to write getopt in bash script


I have a function with a few parameters. For example:

makeUser{
login
email
password}

I want to make flags like -l|--login, -e|--email and -p|--password but I don't know how.

The sample for it should look like the code below:

./script.sh --mode makeUser --login test --email [email protected] -p testxx

How can I achieve that result? I know only how to make it with getopts (short flags).

Should it look like code below?

while true ; do
case "$1" in
    -m|--mode)
        makeUser)
           case "$2" in
              -l|--login)
                 makeUser "$OPTARG"
                    case "$3" in
                       -e|--email)
                           makeUser "$OPTARG"
                              case "$4" in
                                 -p|--password)
                                     makeUser "$OPTARG"
                                     exit $?
                               esac ;;
                    exit $?
                    esac ;;       
            exit $?
            esac ;;    
        makeProject)...
        makeSite)...
    exit $?    
    esac ;;
done

Solution

  • Using while and shift makes a clean solution for getopt-alike behaviour in bash:

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|"-?"|--help)
                shift
                echo "usage: $0 [-v] [--mode MODE] [-l login] [-e email] [...]"
                exit 0
                ;;
            --mode)
                MODE=$2
                shift; shift;
                ;;
            -l|--login)
                LOGIN=$2
                shift; shift;
                ;;
            -e|--email)
                EMAIL=$2
                shift; shift;
                ;;
            -v|--verbose)
                VERBOSE=1
                shift;
                ;;
             *)
                echo "Error: unknown option '$1'"
                exit 1
            esac
    done
    
    # example function makeUser
    makeUser()
    {
        login=$1
        email=$2
    
        echo "function makeUser with login=${login} and email=${email}"
    }
    
    
    if [ "$MODE" == "makeUser" ]; then
        makeUser $LOGIN $EMAIL # ... and so on
    fi