It's common to use "here documents" to simplify input to a program in a script.
e.g.
> cat <<EOF
> This is a random number:
> $RANDOM
> EOF
This is a random number:
9948
But what if you want to capture the output of this? The naive attempt would be to redirect after the second EOF, but this is incorrect as the termination string has to be on a line all by itself.
This is the answer:
> cat <<EOF > /tmp/data.txt
> This is a random number:
> $RANDOM
> EOF
> cat /tmp/data.txt
This is a random number:
24669
Thanks - I was wondering how to do that.
ReplyDeleteThanks, seeing it helped me to solve a similar problem: how to have both here document, output redirection and piping.
ReplyDeleteI did something like the following:
cat <&1 | tee /tmp/output.log
Some test
EOF
cat /tmp/output.log
In my scenario, instead of a cat I was passing a Python script as a here document and I was scratching my head about capturing both standard output and standard error on a log file but having it also shown in the console.
Your post gave me the insight to the syntax, thank you again!
What's about
Deletecmd 2>&1 | tee /tmp/output.log
Cheers Thorsten
So simple, so helpful! Thank you for pointing this out!
ReplyDelete