Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IF statement and multiple options 2

Status
Not open for further replies.

phorbiuz

Technical User
Jul 22, 2004
67
GB
Can someone help with the best way to do this please? I'm looking for the simplest approach with the least amount of lines.

What I have is 3 variables each with their own numeric content. In an ideal world I'd have an if statement along the lines of:

if [[ $variable1 = 1 ]] or if [[ $variable2 = 4 ]] or if [[ $variable3 = 7 ]]
then
take action
fi

Remembering I want to keep this as simple as possible for other people to be able to follow, any suggestions?

Thanks in advance.



 
[ $variable1 -eq 1 -o $variable2 -eq 4 -o $variable3 -eq 7 ] && take action

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
phorbiuz
Beware of your choice of equality - this is a very common error - well, in our team anyway.

The equals sign is string equality. Often, very often you can get away with it but consider the following code fragment.
Code:
var=01
if [ $var = 1 ] #this will fail - 01 is not the same STRING as 1
then
  do_action
fi

if [ $var -eq 1 ] # this is probably what you want - numeric equality
then
  do_action
fi


On the internet no one knows you're a dog

Columb Healy
 
Whenever you have a lot of "if" options, a case statement is usually best...
Code:
case $var in
    [147])  do_action
            ;;
esac    

# or

case $var in
    1|4|7)  do_action
            ;;
esac
When you have to add more to the "if"s, this usually is easier to understand and make changes to.
 
Sam, you test a single variable but the OP test 3 different var ...

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Oops! My bad! I read it as three possible values for one variable.

Nevermind! [bigsmile]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top