How To Use bash For Loop In One Line

How To Use bash For Loop In One Line

In Bash, you can use a for loop in a single line by using the ; symbol to separate the loop statements.

Here is an example of a for loop in a single line:

for i in 1 2 3; do echo $i; done
So‮ww:ecru‬w.lautturi.com

This for loop will iterate over the values 1, 2, and 3, and print each value on a separate line.

The syntax of a for loop in a single line consists of the following elements:

  • for i in 1 2 3: this specifies the loop variable i and the values that the loop will iterate over.
  • do: this marks the beginning of the loop body.
  • echo $i: this is the loop body. It executes the commands inside the loop on each iteration.
  • done: this marks the end of the loop body.

You can use other variables and expressions in the for loop, and include multiple commands in the loop body by separating them with ;.

For example:

for i in 1 2 3; do echo $i; echo "$i squared is $((i*i))"; done

This for loop will iterate over the values 1, 2, and 3, and print each value and its square on a separate line.

You can also use the break and continue statements inside a for loop to control the flow of the loop. The break statement will exit the loop, and the continue statement will skip the rest of the loop body and move to the next iteration.

For example:

for i in 1 2 3; do if [[ $i -eq 2 ]]; then break; fi; echo $i; done

This for loop will iterate over the values 1, 2, and 3, but it will exit the loop after the second iteration, because of the break statement. As a result, only the values 1 and 2 will be printed.

Keep in mind that using a for loop in a single line can make the code more difficult to read.

Created Time:2017-10-29 22:08:34  Author:lautturi