Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "else" in bash case command?

Tags:

bash

filter="yes"
phonenumbers=(123 456 789 987 654 321)
echo "checking inbox now..."
myphonenumber=(7892)

if [[ "$filter" == "yes" ]]; then
    case "${phonenumbers[@]}" in
        *"$myphonenumber"*) echo "filter is on, phone number matches" 
        ;;
        !="$myphonenumber") echo "filter is on but the phone number doesn't match" 
        ;;
    esac
fi

if [[ "$filter" == "no" ]]; then
    echo "filter off"
fi

I try running that script but it doesn't work, how should I display the filter is on but the phone number doesn't match part? I'm still learning, I know I can do it with if else statement but I wonder if I can do it with case too.

like image 822
Lin Avatar asked Feb 16 '15 16:02

Lin


2 Answers

Solved with this *) so the whole code is:

filter="yes"
phonenumbers=(123 456 789 987 654 321)
echo "checking inbox now..."
myphonenumber=(7892)

if [[ "$filter" == "yes" ]]; then
  case "${phonenumbers[@]}" in
    *"$myphonenumber"*) echo "filter is on, phone number matches" ;;
    *)                  echo "filter is on but the phone number doesn't match" ;;
  esac
fi

if [[ "$filter" == "no" ]]; then
  echo "filter off"
fi
like image 186
Lin Avatar answered Sep 18 '22 20:09

Lin


If you are looking for something similar to a default statement of a switch in a C-like language, the following should handle this. Observe the *) clause.

For a bit of reference, http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html

filter="yes"
phonenumbers=(123 456 789 987 654 321)
echo "checking inbox now..."
myphonenumber=(7892)

if [[ "$filter" == "yes" ]]; then
    case "${phonenumbers[@]}" in  
        *"$myphonenumber"*) echo "filter is on, phone number matches" 
        ;; 
        *) echo "filter is on but the phone number doesn't match" 
        ;; 
    esac
fi

if [[ "$filter" == "no" ]]; then
    echo "filter off"
fi
like image 38
h7r Avatar answered Sep 19 '22 20:09

h7r