Magazine

Loop with Pipes and Execute Loop in Background Using Linux Bash Script

Posted on the 21 April 2021 by Satish Kumar @satish_kumar86

Piping the output of a loop to a Linux command

If we need to redirect theoutputof a loop toanyother Linux command such assort, we can even redirect the loop output to be stored in the file:

The following is an example of source codefor_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 scriptwithloops 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 followingfor_15.shscript 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.


Back to Featured Articles on Logo Paperblog