How To Use bash For Loop In One Line

It is possible to use a for loop in bash on a single line. Here is an example:

for i in {1..5}; do echo $i; done

This loop will print the numbers 1 through 5 on separate lines. Here’s a breakdown of how the loop works:

  • for i in {1..5}; sets up the loop to iterate over a range of numbers from 1 to 5, assigning each number to the variable i.
  • do echo $i; specifies the commands to execute for each iteration of the loop. In this case, it simply prints the value of i.
  • done marks the end of the loop.

You can modify the loop to perform any command or set of commands on each iteration, as long as the commands are separated by semicolons (;) and the loop is enclosed in a single line by using semicolons between commands.

Keep in mind that using a one-liner can make code harder to read and maintain. It’s usually better to use multiple lines and format the code for readability.

Leave a Comment