Skip to content

Conditions and loops

We can write conditional statements and loops in bash.

if

  • if [ exp1 condition exp2 ]; then statements; fi.

statement gets executed if condition satisfies for exp1 and exp2.

condition can be any of the following:
-eq equal to.
-ne not equal to.
-gt greater than.
-lt less than.
-a and.
-o or.

These can be used for other conditional statements also.

if else

  • if [ exp1 condition exp2 ]; then statements; else statements; fi

if else if

  • if [ exp1 condition exp2 ]; then statements; elif [ exp1 condition exp2 ] then statements; else statements; fi

Exercise

  • Try out if, if else and if else if by printing some string according to the condition.

for

To run a command multiple times, we can use bash loops.
For running n times using for loops.

  • for i in {1..n}; do command; done

The following is an alternative for the above loop.

  • for((i=1;i<=n;i+=1)); do command; done

Exercise

  • Print the multiplication table of 9 using for loop in both the ways mentioned above.

while

Bash also has while loops.

  • while condition; do command; done

Examples:

  • while true; do echo "hello"; done
  • while [ $i -le 5 ]; do echo $i; done

Exercise

  • Do the same exercise as for but now using while.