2

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
Incognito
  • 135
  • 4
  • 14
  • Please consider running your script through [shellcheck](https://www.shellcheck.net) first, to fix all the machine detectable issues like why your script always prints "Not a boolean value". Then edit and update if you still have problems – that other guy Jun 12 '19 at 01:48
  • @Pluto : How did you invoke this script? – user1934428 Jun 12 '19 at 06:40
  • 1
    @Pluto : `flag` will *always* be different from either _true_ or _false_. – user1934428 Jun 12 '19 at 06:41
  • I just noticed you unmarked the answer, have you experienced any issue with it? If so, let me know and I will try to help you to solve it. – danrodlor Jun 12 '19 at 11:44

1 Answers1

4

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
danrodlor
  • 1,329
  • 8
  • 16