Bash for Loop 1 to 10

Bash - For loop 1 to 10

Using for Loop with seq Command

To loop from 1 to 10 in the Bash shell:

  • Use the for keyword to start the for loop.
  • Use i as a loop variable, which is accountable for taking values from 1 to 10.
  • Use the $(seq 1 10) expression, which is a command substitution executing the seq command to produce a sequence of numbers from 1 to 10.
  • Use the do keyword to mark the starting of the for loop’s body.
  • Use the echo command to print the value of the i variable on the bash console that we created in step-2.
  • Use the done keyword to mark the for loop’s end.

Here, we used the seq command, which is used in Linux to generate a sequence of numbers from the specified FIRST to the specified LAST in steps of INCREMENT. This command is helpful for loops such as for and while, etc.

We can use the seq command in the following three ways:

  • seq 10 – this command will generate numbers starting from 1 to 10 by increment 1.
  • seq 2 10 – this command will generate numbers starting from 2 to 10 by incrementing 1.
  • seq 2 2 10 – this command will generate numbers beginning from 2 to 10 by incrementing 2.

In the seq command, the first value is the starting number, the last value is the ending number, and the middle value represents the increment.

Using for Loop with C-sytle Syntax

To loop from 1 to 10 in the Bash shell:

  • Use the for keyword to start the for loop.
  • Use j to hold the value from 1 to 10 incremented by 1 (one value in each iteration).
  • Use the do keyword to mark the starting of the for loop’s body.
  • Use the echo command to print the value of the i variable on the bash console we created in step-2.
  • Use the done keyword to mark the for loop’s end.

Using for Loop with Curly Braces

To loop from 1 to 10 in the Bash shell:

  • Use the for keyword to start the for loop.
  • Use i to hold the value from 1 to 10 incremented by 1 (one value in each iteration).
  • Use curly braces with the .. operator as {1..10} to specify the range; here, it is 1 to 10.
  • Use the do keyword to mark the starting of the for loop’s body.
  • Use the echo command to print the value of the i variable on the bash console we created in step-2.
  • Use the done keyword to mark the for loop’s end.

That’s all about Bash for loop 1 to 10.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *