Friday, December 11, 2009

Redirecting the output from a "here document"

This had me confused for a few minutes, so I thought I'd post.

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

4 comments:

  1. Thanks - I was wondering how to do that.

    ReplyDelete
  2. Thanks, seeing it helped me to solve a similar problem: how to have both here document, output redirection and piping.

    I 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!

    ReplyDelete
    Replies
    1. What's about

      cmd 2>&1 | tee /tmp/output.log

      Cheers Thorsten

      Delete
  3. So simple, so helpful! Thank you for pointing this out!

    ReplyDelete