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 |
| -z | the length of STRING is zero |
| -n | the length of STRING is nonzero |
| Integer Operators |
| -eq | is equal to |
| -gt | is greater than |
| -ge | is less than or equal to |
| -le | is less than or equal to |
| -lt | is less than |
| -ne | is not equal to |
| File Operators |
| -ef | have the same device and inode numbers |
| -nt | is newer (modification date) than |
| -ot | is older than |
| -e | FILE exists |
| -f | FILE exists and is a regular file |
| -s | FILE exists and is greater than zero |
| Expression Operators |
| ( EXPRESSION ) | EXPRESSION is true |
| ! EXPRESSION | EXPRESSION is false |
| EXPRESSION1 -a EXPRESSION2 | logical AND |
| EXPRESSION1 -o EXPRESSION2 | logical 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.