Shell – Use HERE file and redirect output of command

io-redirectionshell

I have the following code in a batch script:

mpirun -np 6 ./laplace <<END
100
100
100
0.01
100
3
2
1
END
| tail -n 1 > output

But it isn't working. What I want it to do is to use the HERE file as input to the mpirun command, and then pipe the output to the tail command. However, I think the HERE file and tail output things are getting confused.

How should I write this so that it does what I want?

Best Answer

What you've written in the first line looks like a complete command (a “(compound) list” in shell terminology), so the shell treats it as a complete command. Since there's a here-document start marker (<<END), the shell then reads the here-document contents, and then starts a new command. If you want to put the here-document in the middle of a list, you need to indicate to the shell that the list is not finished. Here are couple of ways.

mpirun -np 6 ./laplace <<END |
…
END
tail -n 1 > output
{ mpirun -np 6 ./laplace <<END
…
END
} | tail -n 1 > output

Or, of course, you can make sure the command completely fits in the first line.

mpirun -np 6 ./laplace <<END | tail -n 1 > output
…
END

The rule to remember is that the here-document contents starts after the first unquoted newline after the <<END indicator. For example, here's another obfuscated way of writing this script:

mpirun -np 6 ./laplace <<END \
| tail -n $(
…
END
             echo 1) > output