Home Uncategorized For loops in bash

For loops in bash

by The Linux Digest Guy

You can use for loops in bash just like in any other programing language. The basic syntax is like this:

for variable-name in 1 2 3
do
  list-of-commands
done

One line for loop in bash

To do a quick one-liner with for, we use a semicolon to separate each line. In this example, we will give for a list of 4 items to iterate through.

~$ for i in 1 2 3 4; do echo "This is line number $i"; done;
This is line number 1
This is line number 2
This is line number 3
This is line number 4

For loop in a bash script

When writing a script. We don’t need to use the semicolon as in the example above. This time we write each part of the command on a separate line. This example will print exactly the same output as the one-liner we just did.

for i in 1 2 3 4
do
        echo "This is line number $i"
done

Use a command to get a list of items

Instead of giving for a long list of items to iterate through, we can also wrap a command in $( ) to get the list. In this example we use the seq command to get a list of numbers 1 through 4. This will output exactly the same as above.

for i in $( seq 1 4 )
do
        echo "This is line number $i"
done
2

Related Posts

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy