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 value in 10 5 27 33 14  25 
      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:


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 ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.