Search code examples
bashscriptingshgetopts

Checking for lack of flags in bash


If I were to do something like this to process arguments in bash, how would I check if there were no arguments? It doesn't seem to go to the *) case, but I'd still like to put a usage statement in there somewhere.

while getopts 'ias' flag; do
  case "${flag}" in
    i) ifl='true' ;;
    m) afl='true' ;;
    n) sfl='true' ;;
    *) error "Invalid option ${flag}" ;;
  esac
done

Solution

  • Before the while loop, do this

    if (( $# == 0 )); then
        echo "you must specify one of -i or -a or -s"
        exit 1
    fi
    

    or, after the while loop, you can do this

    if [[ $ifl != true && $afl != true && $sfl != true ]]; then
        echo "you must specify one of -i or -a or -s"
        exit 1
    fi