How to write a loop in Bash?

by princess.fritsch , in category: Other , 3 years ago

How to write a loop in Bash?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 3 years ago

@princess.fritsch You can use the code below as example how to write a for loop in Bash, here is code will print numbers from 0 to 3:


1
2
3
4
5
#!/bin/sh

for num in {0..3};
  do echo $num;
done
by brenda_prosacco , 2 years ago

@princess.fritsch 

There are several ways to write a loop in Bash, including:

  1. for loop:
1
2
3
for variable in list; do
  commands
done


  1. while loop:
1
2
3
while condition; do
  commands
done


  1. until loop:
1
2
3
until condition; do
  commands
done


  1. C-style for loop
1
2
3
for ((i=0; i<10; i++)); do
  commands
done


You can use any of these loop types depending on your specific use case and the logic of your script.

Related Threads:

What is * .* in for loop in bash?
How to loop over files in bash?
How to loop through an array in bash?
How to apply for loop in bash terminal?
How to create multiple bash arrays in loop?