Читать книгу Kali Linux Penetration Testing Bible - Gus Khawaja - Страница 76

Loops

Оглавление

You can write loops in two different ways: using a while loop or using a for loop. Most of the programming languages use the same pattern for loops. So, if you understand how loops work in Bash, the same concept will apply for Python, for example.

Let's start with a while loop that takes the following structure:

while [[ condition ]] do do something done

The best way to explain a loop is through a counter from 1 to 10. We'll develop a program that displays a progress bar:

#!/bin/bash #Progress bar with a while loop #Counter COUNTER=1 #Bar BAR='##########' while [[ $COUNTER -lt 11 ]] do #Print the bar progress starting from the zero index echo -ne "\r${BAR:0:COUNTER}" #Sleep for 1 second sleep 1 #Increment counter COUNTER=$(( $COUNTER +1 )) done

Note that the condition ( [[ $COUNTER ‐lt 11]] ) in the while loop follows the same rules as the if condition. Since we want the counter to stop at 10, we will use the following mathematical formula: counter<11 . Each time the counter is incremented, it will display the progress. To make this program more interesting, let it sleep for one second before going into the next number.

On the other hand, the for loop will take the following pattern:

for … in [List of items] do something done

We will take the same example as before but use it with a for loop. You will realize that the for loop is more flexible to implement than the while loop. (Honestly, I rarely use the while loop.) Also, you won't need to increment your index counter; it's done automatically for you:

#!/bin/bash #Progress bar with a For Loop #Bar BAR='##########' for COUNTER in {1..10} do #Print the bar progress starting from the zero index echo -ne "\r${BAR:0:$COUNTER}" #Sleep for 1 second sleep 1 done

Kali Linux Penetration Testing Bible

Подняться наверх