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
:
#!/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:
5 10 14 25 27 33
In the preceding script, the for
loop iterates through a list of numbers which is unsorted. The numbers are printed in the body of the loop, which are enclosed between do
and done
commands. Once the loop is complete, the output is piped to the sort
command, which in turn is performing ...
Get Learning Linux Shell Scripting now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.