Primer: Bash Loops: in order to, while and until

Contents

Most programming languages ​​support multiple alternatives for looping lines of code. Bash natively supports 'while' loops, loops' up’ and the 'for loops’ best known. This post presents and analyzes the three.

Which are Bash Loops?

To set this a little better, we should start with the question what are loops. Loops are a construction of the programming language, that enables a developer to repeat (In other words, repeat) certain parts, the whole, of the code within that loop definition. Now it's easy to set Bash Loops like any looping programming language construct used in bash!

Bash natively supports 'for' based loops, ‘until’ y ‘while’. Each of these has its own advantages, but you can already get an idea of ​​their meanings just by looking at the idiom of the main word. As an example, 'until’ leads one to naturally think of 'doing something until’ and this is what bash loops 'up to' do; repeat a certain amount of code (the whole) until a certain condition is met.

Equivalently, los bucles ‘while’ continue to run until a condition is no longer true. To end, the 'for loops’ are repeated, as an example, a defined number of times, equivalent to how we would write 'for 70 times, make…'. This helps us to logically understand the unique features each loop provides and to implement more readable code..

for Based bash loops

For the purposes of this post, we will see the newest way to set Bash for loops. A somewhat older and less modern definition of for loops in bash can, as an example, look like this: for i in $(seq 1 5); do echo $i; done. Let's compare this to a cleaner look, better structured and modern. for circle:

for ((i=1;i<=5;i++)); do echo $i; done

A loop based on Bash for

That simple for One-liner bash based on (a definition often used in Linux circles / Bash to conceptualize a mini-script written on a single line) will print the numbers of the 1 al 5 in sequential order. We set a starting value for the i variable ($i) assigning the value 1 the same, as the first part of our for loop definition, finished by a ; delimiter.

Next, we specify that we only have one to upload ‘Less than or equal to five’ through use i<=5. Later we indicate what should happen at the end of each round, and that is increasing the variable i by one, O, in a commonly used encoding abbreviation (included in the C language ++, as an example), this translates as i++.

To finish we specify the start of our loop code using do, In other words, after finishing our for loop definition, just like any other statement ending, with ; before do. Additionally we specify the end of our loop code using done and we echo (to print) the value of our variable I between do and done.

Also note specifically that the do the clause itself does not end with ;, and doing so would cause an error. Consider the do a prefix to what to do, and it makes more sense. This maybe one of the reasons why it is sometimes cleaner to put things in a multi-line script, Given the do it may just be the last word on a line.

Even when setting other types of loops, seguiremos manteniendo el do and done clauses, y siempre nos aseguraremos de terminar nuestra definición de bucle (In other words, before do) with ;, así como finalizar el final de cada declaración individual dentro de nuestra do...done definición de bucle con ;.

Pongamos esto en un pequeño script para ver más claramente cómo pueden funcionar las cosas de esa manera:

#!/bin/bash

for ((i=1;i<=10;i+=2)); do 
  echo $i
done

Un script de bucle basado en Bash for

Después de hacer que el script sea ejecutable con chmod +x test.sh, ejecutamos lo mismo. Se introdujeron algunos pequeños cambios en el guión. Watch how this time, we are increasing the variable i for two each time. This is done using another encoding abbreviation, namely i+=2 which can be read as increase and in two. You can also write i=i+2 In the same place, and it works exactly the same.

We see that we start in 1and increase in 2 every time we go through the loop, ending in 9. The reason why it ends in 9 is that the maximum value is 10. Because, after 9 the next value would be 11, which is greater than 10 and that's why it doesn't show / links.

Also consider how ; was removed after the echo line. This is because it is not necessary to end the end of a statement if there is a situation instead / end of line character. This is the case here; we don't have any other command after the echo $i and the line ends immediately (spaces at the end of the line would also be fine, the principle is just not to have another command unless that new command has the prefix (and the previous one finished) for ;).

weather Based bash loops

Next, let's take a look at a bash loop, using the same do...done loop definition, we can establish a while the bash based loop to be executed as long as a given condition is true.

i=1; while [ $to the 5 ]; do echo $i; i=$[ i + 1 ]; done

A loop based on Bash while

In this example, we do the same as our first for based loop example. Although the definition seems more complex (and that's why one for loop may be more suitable for this particular use case), it is interesting to see how we can establish a weather loop in the same way.

Here we first set our i variable, manually, in a separate command terminated by ;, in order to 1. Next, we started a weather loop where we set a condition, in a way very equivalent to the definition of a if statement (there is a link at the end of this post to a post about if statements for more information), where we are checking if the i the variable is less than or equal (-le) later 5.

After this we have our frequent do...done block in which echo our variable, and subsequently, in a new statement, manually, increase the value of our i variable by one in a mathematical calculation as defined by the $[...] Bash calculation idioms. Next, let's review a up to bash loop based

until Based bash loops

Armed with what we've learned so far, now we can more easily examine the following until bash loop based:

i=1; until [ $i -gt 5 ]; do echo $i; i=$[ i + 1 ]; done

A loop based on bash until

Here we look for the condition I greater than 5 to come true. Until that moment (In other words, a until loop based on), we will print (using echo) our variable I and increase the same with one, same as our previous weather example based.

We can see how the syntax of the until command is very equivalent to weather command. Also note that, Unlike for based command, these commands look for a certain condition to persist (with weather), or for a certain condition to start (with until). Esto además posibilita utilizar otros comandos que pueden devolver una salida equivalente a verdadero / fake, as an example grep -q:

echo 1 > a
while grep -q '1' ./a; do echo 'yes'; sleep 5; done

Verificando un estado verdadero usando grep -q en un bucle Bash basado en while

Aquí sumamos el número 1 a un archivo llamado ay compruebe la existencia del número 1 dentro de ese archivo usando un grep -q (un grep silencioso). Seguimos haciéndolo (In other words weather) hasta que ya no sea cierto. Aunque es cierto, imprimimos el texto Yes y pausa el bucle durante cinco segundos con sleep 5. Observe cómo cada comando termina con ; again.

After about 17 seconds, we interrupt our script using CTRL + c, which is the universal method to stop a running procedure in bash (at the same time of the CTRL + z Stronger and more effective than pausing a procedure immediately, But that's for another post!!)

Ending

In this post, we check the 'for' loops, ‘while’ y ‘until’ which are natively available in Bash. If you are interested in more bash, take a look at conditional tests in bash: if, then, else, elif and bash functions and local variables.

Enjoy!

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.