LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   multiple if condition in a bash script (https://www.linuxquestions.org/questions/programming-9/multiple-if-condition-in-a-bash-script-4175455801/)

grima 03-27-2013 11:09 AM

multiple if condition in a bash script
 
Hi,

I've a question concerning multiple if 'conditions' in bash.

My code looks as follows:

Code:

#!/bin/bash
for i in {1..20..1}
do

  if [[ $i -eq {7 || 11 || 18} ]]
  then
  echo "Welcome $i times"
  fi

done

For example, the 'echo' in the if condition should be for the numbers 7,
11, 18.
But it doesn't do.

Does somebody know how to do that?

Best, grima

unSpawn 03-27-2013 02:01 PM

Why not use a case statement: 'case $i in 7|11|18) echo "Welcome $i times";; esac;'?

colucix 03-27-2013 02:45 PM

Moved: This thread is more suitable in Programming and has been moved accordingly to help your thread/question get the exposure it deserves.

kooru 03-28-2013 03:18 AM

Hi and welcome to LQ!

Try this:

Code:

#!/bin/bash
for i in {1..20..1}
do

  if [[ $i -eq 7 || $i -eq 11 || $i -eq 18 ]]
  then
  echo "Welcome $i times"
  fi

done


David the H. 03-28-2013 05:09 AM

If you only need to match exact number strings, I second colucix's recommendation for a case statement. They're almost always more efficient than if tests.
Code:

#!/bin/bash
for i in {1..20}; do

    case i in
        7|11|18) echo "Welcome $i times" ;;
    esac

done

But if you need to do other numerical comparisons, then a bash "((..))" arithmetic operator is the best choice.

Code:

#!/bin/bash
for i in {1..20}; do
    if (( i == 7 || i == 11 || i >= 18 )); then
        echo "Welcome $i times"
    fi
done

When using bash or ksh, it's recommended to use [[..]] for string/file tests, and ((..)) for numerical tests. Avoid using the old [..] test unless you specifically need POSIX-style portability.

http://mywiki.wooledge.org/BashFAQ/031
http://mywiki.wooledge.org/ArithmeticExpression


And two other minor points:

1) You don't need a step operator in brace expansion if you're just counting by ones anyway.

2) Many scripters also feel that it's better to place the "do/then" keywords on the same line as the "for/while/until/if" keywords, as they are not separate commands but are paired with the opening keyword to bracket the test/input string. Putting them together on one line thus helps to better visually separate the outside block from the inside block.

Scripting With Style


All times are GMT -5. The time now is 02:08 AM.