Loops are one of the fundamental concepts of programming languages. Loops are handy when you want to run a series of commands over and over again until a certain condition is reached.
I am not gonna explain anything here, because you have already learned array, dictionary, statements and etc. If you haven’t yet, please visit my bash page to read all listed chapters.
Old way of 4 loop, which we don’t use anymore.
1
2
3
for (( x=0; x<5; x++ )); do
echo $x
done
Now let’s talk about new way of using 4 loops in Bash Scripting.
Loop with Brace Expansion.
1
2
3
for x in {1..5}; do
echo $x
done
Loop with Shell Execution.
1
2
3
for x in $(ls *.txt); do
echo $x
done
Loop with an Array.
1
2
3
4
5
array=("Mango" "Apple" "Banana")
for x in ${array[@]}; do
echo $x
done
Loop with Dictionary.
1
2
3
4
5
6
7
8
declare -A dict
dict[name]="Yafiz Abraham"
dict[course]="Bash Scripting"
dict[platform]="YouTube"
for key in "${!dict[@]}"; do
echo "$key : ${dict[$key]}"
done
cat-while
Loop.
1
2
3
cat file.txt | while read x; do
echo $x; echo 'NEW LINE'
done
Loop with while. Stop when it reaches to 4th value
1
2
3
4
num=1
while [ $num -lt 4 ]; do
echo "num: $((num++))"
done