Loop with Pipes and execute loop in background using Linux bash script

Piping the output of a loop to a Linux command

If we need to redirect the output of a loop to any other Linux command such as sort, we can even redirect the loop output to be stored in the file:

The following is an example of source code for_14.sh:

for_14.sh

#!/bin/bash 
for value in 10 5 27 33 14  25 
do 
      echo  $value 
done | sort -n 

Let’s test the program:

$ chmod +x for_14.sh
$ ./for_14.sh

The following will be the output after executing the preceding commands:

Output:

51014252733

In the preceding script, the for loop iterates through a list of numbers that is unsorted. The numbers are printed in the body of the loop, which are enclosed between the do and done commands. Once the loop is complete, the output is piped to the sort command, which, in, turn performs a numerical sort and prints the result on screen.

Running loops in the background

In certain situations, the script with loops may take a lot of time to complete. In such situations, we may decide to run the script containing loops in the background so that we can continue other activities in the same terminals. The advantage of this will be that the Terminal will be free to give the next commands.

The following for_15.sh script is the technique to run a script with loops in the background:

for_15.sh

#!/bin/bash 
for animal in Tiger Lion Cat Dog 
do 
     echo $animal 
    sleep 1 
done & 

Let’s test the program:

$ chmod +x for_15.sh
$ ./for_15.sh

The following will be the output after executing the preceding commands:

Output:

TigerLionCatDog

In the preceding script, the for loop will process the animals TigerLionCat, and Dog sequentially. The variable animal will be assigned the animal names one after another. In the for loop, the commands to be executed are enclosed between do and done. The ampersand after the done keyword will make the for loop run in the background. The script will run in the background till the for loop is complete.

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

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

7 + 2 =