MAK
MAK

Reputation: 7260

bash- IF with multiple condition using IN

I have the following script to check for multiple condition occurred.

Script:

#!/bin/bash
echo "1.Add,  2.Sub, 3.Mul, 4.Div"
echo "Enter your choice:"
read ch

#Here i want to check the condition for 1, 01 and also 001
if [ $ch = 1 ]
then
     echo "Addition goes here"
...
...
fi

Note: How can i use multiple condition using IN?

Like:

if  [ $ch IN ('1','01','001') ]

Upvotes: 0

Views: 77

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

With bash, you can write:

if [[ $ch == @(1|01|001) ]]

Inside [[ ... ]], the == operator does pattern matching, and the extended pattern @(pattern-list) matches one or more of the given pattern.

docs:
https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs
https://www.gnu.org/software/bash/manual/bashref.html#Pattern-Matching

Upvotes: 0

Thomas
Thomas

Reputation: 181725

Use a case statement instead:

case $ch in
  1|01|001)
    echo "Addition goes here"
    ;;
  ...
  *)
    echo "Invalid input"
esac

Upvotes: 3

Related Questions