Bash compound commands and redirection
I've been using Linux for about 15 years. There are a lot of features I don't know and some that I've used but not often enough or to the full extent of possibilities.
Recently, I had written a bash
function, which required saving the output of a for
loop to a file. I knew that compound commands support redirection, but it didn't strike me at that time as I haven't had to use them often.
Here's a simplified version of the function I wrote first:
pf()
{
> input.txt
for f in "$@" ; do echo "$f $f.bkp" >> input.txt ; done
cmd input.txt > output.txt
}
Having to empty the file using > input.txt
got me thinking that perhaps I was missing some obvious solution. Few days later, I realized that instead of using >>
during every iteration of the loop, I should have just applied >
to the loop itself.
pf()
{
for f in "$@" ; do echo "$f $f.bkp" ; done > input.txt
cmd input.txt > output.txt
}
echo
and cmd
in the above examples are just placeholders for illustration purposes. I needed both input.txt
and output.txt
after calling the function, which is why I didn't use |
or process substitution.