Loops in bash scripting

Here are some examples on how to use loops in bash scripting.

# FOR loop

for i in {1..10}; do ls {filename}$i ; done
for i in $(seq 1 10); do echo {filename}$i ; done
for i in `seq 1 10` ; do echo {filename}$i ; done

# WHILE loop

while true; do {command} && sleep 1;done

# UNTIL loop

# In one line
let u=10 ; until [ $u -eq 0 ];do echo $u && let u-=1 ; done

# With line breaks
#!/bin/bash
 let u=10
until [ $u -eq 0 ]; do
 echo $u && let u-=1
done

# IF ... THEN ...ELSE Statement

# In one line
if [ $p -eq 34 ]; then echo $p ; else echo "Foobar" ; fi

# With line breaks
#!/bin/bash
if [ "foo" -eq "foo" ]; then
 echo "expression evaluated as true"
else
 echo "expression evaluated as false"
fi

# IF ... THEN ... ELIF Statement

#!/bin/bash
if [ "foo" == "foo" ]; then
 echo "expression evaluated as true"
elif [ 4 -lt 5 ]; then
 echo "expression evaluated as true"
else
 echo "expression evaluated as false"
fi

# CASE Statement

#!/bin/bash
case $1 in
  start)
   # Commands to execute
   ;;
  stop)
   # Commands to execute
   ;;
  status)
   # Commands to execute
   ;;
  *)
   # if no matches do this (optional)
   ;;
esac

Most used comparison operators

String Operators
==the strings are equal
!=the strings are not equal
-zthe length of STRING is zero
-nthe length of STRING is nonzero
Integer Operators
-eqis equal to
-gtis greater than
-geis less than or equal to
-leis less than or equal to
-ltis less than
-neis not equal to
File Operators
-efhave the same device and inode numbers
-ntis newer (modification date) than
-otis older than
-eFILE exists
-fFILE exists and is a regular file
-sFILE exists and is greater than zero
Expression Operators
( EXPRESSION )EXPRESSION is true
! EXPRESSIONEXPRESSION is false
EXPRESSION1 -a EXPRESSION2logical AND
EXPRESSION1 -o EXPRESSION2logical OR

Control flow

break is used when the execution of the entire loop needs to be interrupted.

continue will transfer control to the next set of code but will not stop the execution of the current loop.

exit is self explanatory.

return is used to return data back.


Terms of Service Privacy Security

© 2025 Julian's Corner. All rights reserved