Search code examples
bashloopsgetopts

bash getopts loop not iterating


I have a simple loop i use in a lot of my bash scripts, yet this particular one doesn't seem to work.

#!/bin/bash
function main
{
    echo here
    while getopts "Ah" cli_opt; do
      case ${cli_opt} in
        A)
            echo "op A"
            start_all
            return $?
        ;;
        *)
            echo invalid option
            showHep
            exit 1
        ;;
        h)
            showHelp
            exit 0
        ;;
        \?)
            invalid option
            showHelp
            exit 1
        ;;
        :)
            option -$OPTARG requires an argument
            showHelp
            exit 1
         ;;
      esac
    done
}

main
exit 0

Regardless of how i call it, it only reaches "here".


Solution

  • The fix, change:

    main
    

    to:

    main "$@"
    

    "$@" is an array containing all of the arguments. You'll need to pass this array to your main function.