Search code examples
bashflags

How can I handle flags without parameters in bash without using getopts?


I am perfectly able to manage flags with parameters with this syntax:

while [[ $# -gt 1 ]]
do
key="$1"

case $key in

-c)
ARGUMENT_OF_C_FLAG="$2"
shift # past argument
;; 
*) 
;;
esac
done

How can I use the same syntax (without getopts) to manaage flags without parameters?

I try to use the same syntax for flags without parameter but it didn't work. For instance for a flag c with parameter and a flag d without parameters, I used without success

while [[ $# -gt 1 ]]
do
key="$1"
case $key in

-c)
ARGUMENT_OF_C_FLAG="$2"
shift # past argument
;; 
-d)
IS_d_FLAG_SET=1
;;
*) 
;;
esac
done

Solution

  • first you have to test with ge not gt or you're not entering the loop when there's only one switch without option.

    Then you have to shift at each loop or you'll have infinite loop

    The shift you were performing when there's an argument got past the option, not the argument, and the error was compensated by gt instead of ge in the while.

    while [[ $# -ge 1 ]]
    do
    key="$1"
    case $key in
    
    -c)
    ARGUMENT_OF_C_FLAG="$2"
    shift # past switch, argument will be skipped by the shift below
    ;; 
    -d)
    IS_d_FLAG_SET=1
    ;;
    *)
    echo "unexpected option $key"
    ;;
    esac
    shift
    done
    
    echo $ARGUMENT_OF_C_FLAG
    echo $IS_d_FLAG_SET