User Tools

Site Tools


programming-languages:bash:loops

Loops

For-loop

#!/bin/bash
i=1
for file in *; do
echo "$i - $file"
i=$((i+1))
done

Note: the use of * allows to loop over the files in the specified directory.

Test on strings

expression is TRUE if
<str> <str> is not null
-n <str> <str> length is greater than zero
-z <str> <str> length is zero
<str1> == <str2> <str1> and <str2> are equal
<str1> != <str2> <str1> and <str2> are not equal
<str1> > <str2> <str1> comes after <str2> in lexicographically order
<str1> < <str2> <str1> comes before <str2> in lexicographically order

To check if <sub-str> is in <str> use:

#!/bin/bash
 
str="string"
if [[ "$str" == *ing* ]]; then
echo "partially match"; else
echo "no match"
fi

Test on integers

expression is TRUE if
<int1> -eq <int2> <int1> is equal to <int2>
<int1> -ne <int2> <int1> is not equal to <int2>
<int1> -le <int2> <int1> is less than or equal to <int2>
<int1> -lt <int2> <int1> is less than <int2>
<int1> -ge <int2> <int1> is greater than or equal to <int2>
<int1> -gt <int2> <int1> is greater than <int2>

While-loop

#!/bin/bash
i=1
while $i -le 5; do
echo "$i"
i=$((i+1))
done
programming-languages/bash/loops.txt · Last modified: 2020/06/27 21:05 by tormec