Is there an easy way to test all the possibilities of the yes / no option in Bash?

I am trying to test for different possibilities Yes / No. Below code works fine, but is there an easy way to do this.

Note. I am using bash version 2.02.0.

read -p "Using dest path :${DESTPATH}" flag;
OPT=$(echo $flag|awk '{print tolower($0)}')
if [[ ${OPT:0:1} != 'y' ]]; then
     echo "Exiting..."; return
fi
+4
source share
3 answers

You don't need to call at all awk. You can use globbing:

read -p "Using dest path :${DESTPATH}" flag

if [[ $flag != [yY]* ]]; then
     echo "Exiting...";
     exit 1
fi

[yY]*will match any line starting with yory

+6
source
case $flag in [Yy]* | sure | absolumatively)
    ;;
  *)
    echo Exiting
    exit 1;; 
esac

It is portable to traditional and POSIX sh. If you are in Bash version 4, you can check ${flag,,}that the value normalizes to lowercase.

+3
source

typeset -l flag : .

@anubhava , .

typeset -l flag
read -p "Using dest path :${DESTPATH}" flag
if [[ $flag != y* ]]; then
     echo "Exiting...";
     exit 1
fi
+2

All Articles