Bash Scripting – Processing Loop outputs
Finally, you can either pipe or redirect the output of a loop within your shell script. You do this by adding the processing command to the end of the done command:
for file in /home/rich/* do if [ -d “$file” ] then echo “$file is a directory” elif echo “$file is a file” fi done > output.txt
$ cat test23 #!/bin/bash # redirecting the for output to a file for (( a = 1; a < 10; a++ )) do echo “The number is $a” done > test23.txt echo “The command is finished.” $ ./test23 The command is finished. $ cat test23.txt The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 $
$ cat test24 #!/bin/bash # piping a loop to another command for state in “North Dakota” Connecticut Illinois Alabama Tennessee do echo “$state is the next place to go” done | sort echo “This completes our travels” $ ./test24 Alabama is the next place to go Connecticut is the next place to go Illinois is the next place to go North Dakota is the next place to go Tennessee is the next place to go This completes our travels $
The state values aren’t listed in any particular order in the for command list. The output of the for command is piped to the sortcommand, which changes the order of the for command output. Running the script indeed shows that the output was properly sorted within the script.