Search code examples
bashshellfile-descriptorio-redirection

How to read only the first line of the output from a file descriptor?


I have output which is coming from fd3 from a program of which I am redirecting to a file as such:

program 3> output.log

In this instance I only need the first line provided by the program to be written to the log and do not want to keep a write handle open to this file for the life of the program.

How can I read only the first line? I think I can use the shell command read but I don't know how to use it for anything other than stdout. Note that I do not want to redirect fd3 to stdout to then use read as I am capturing stdout to another log.


Solution

  • You can capture the first line of an arbitrary file descriptor in this way:

    $ (printf '%s\n' foo bar >&3) 3> >(head -n1)
    foo
    

    This prints two lines to FD 3 and redirects that to standard input of head. If you want to store that result to a file simply redirect within the process substitution.