How to use for loops in Linux

Home > Search > How-to
  by

for loop can be used to iterate through a loop a set number of times. 

  • Line 2 creates the for loop with a variable named foo that contains a string of numbers
  • Line 3 starts the loop
  • Line 4 echo's the variable named foo, which creates the output
  • Line 5 ends the loop
1  #!/bin/bash
2  for foo in 12345
3  do
4    echo $foo
5  done

 

The prior for loop will produce this output.

12345

 

Another example.

#!/bin/bash
content="$(ls)"
for myContent in $content
do
  echo $myContent
done

 


Array

Let's say you have an array of fruit.

fruit=(apple banana orange grape)

 

The following for loop will loop through each item in the array.

#!/bin/bash

fruit=(apple banana orange grape)

for myFruit in ${fruit[@]}
do
  echo $myFruit
done

 

Running the script will produce the following output.

apple
banana
orange
grape

 


Split at new line

By default, a for loop will split at a white space. For example, let's say you have content such as "Hello World How are you today". By default, a for loop will do the following.

Hello
World
How
are
you
today

 

Setting the IFS (Internal Field Separator) to split at a new line fixes this issue. At the end of your script, unset IFS.

IFS=$'\n'
. . .
your for loop here
. . .
unset IFS

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments