Search code examples
bashshellscriptinggetopts

Bash: default boolean value in getopts


I want to include a default option in my script where if the user uses this option, set the flag to true or it should be false by default. It seems that the script is not accepting false or true as boolean value. How can I make it boolean?

flag=

instructions() {
  echo " -a File name" >&2
  echo " -f optional boolean" flag=${flag:-false}
}

while getopts ":a:fi" option; do
  case "$option" in
    a ) file=$OPTARG;;
    f ) flag=true;;
    u )  
       instructions
       ;;
    \?)
      echo "Not valid -$OPTARG" >&2
      instructions
      ;;
    : ) echo "args required";;
  esac
done

if [[ "$flag" != true || "$flag" != false ]]; then
  echo "Not a boolean value"
fi

Solution

  • Check this, I made some fixes to your script (commented in the code) along with a proper formatting.

    #!/bin/bash
    
    # Set the default value of the flag variable
    flag=false
    
    instructions() {
      echo "Usage: $0 [ -a FILE ] [ -f ]" >&2
      echo " -a File name" >&2
      echo " -f optional boolean flag=${flag:-false}" >&2
    }
    
    
    # If the script must be executed with options, this checks if the number of arguments
    # provided to the script is greater than 0
    if [ $# -eq 0 ]; then
        instructions
        exit 1
    fi
    
    while getopts ":a:fi" option; do
      case "${option}" in
        a ) 
           file="$OPTARG"
           ;;
        f ) 
           flag=true
           ;;
        i ) # "u" is not a valid option
           instructions
           exit 0
           ;;
        \?)
           echo "Option '-$OPTARG' is not a valid option." >&2
           instructions
           exit 1
           ;;
        : )
           echo "Option '-$OPTARG' needs an argument." >&2
           instructions
           exit 1
           ;;
      esac
    done
    
    # Since a variable can't have 2 values assigned at the same time, 
    # you should use && (and) instead of || (or)
    if [[ "$flag" != true ]] && [[ "$flag" != false ]]; then
      echo "Not a boolean value"
    fi
    
    exit 0