0

I am writing the shell scripts to start a service on Linux.

I want to start a program, and save its pid to the pid file (so service can stop it again).

I also want to capture the first few (100, say) lines of its standard output to a file, and discard the rest (as there is a lot of output, so the file could get far too large if I saved it all).

I have tried the following code:

    (program 2>&1 &
    echo $! >flags/program.pid ) | head -n 200 >/jumbo/program/log &

However, after this is run, the log file is empty.

Could this be because there aren't a 100 lines yet?

** IMPORTANT ** I DO NOT want to capture the entire output of the process - I want to discard all but the first 100 or so lines, otherwise the disk will rapidly fill up.

I have read the alleged duplicate at Bash: Capture output of command run in background, and come up with the following proposed code:

    exec 3< <(program 2>&1 &
    echo $! >flags/program.pid )
    (head -n 100 <&3 >program.log
    cat <&3 >/dev/null)&

However, I don't understand the underlying mechanisms here, and would like to be reassured that this won't gobble up resources (it may be running for years at a time, as it is a service, and the program outputs a lot of data).

Also, obviously, suggestions for improvements welcome.

Community
  • 1
  • 1
Nikki Locke
  • 2,759
  • 6
  • 29
  • 53
  • It is because you are not actually capturing the command output of the background process started. How long is the command output? Can it be saved in a file? is it a constantly increasing one? – Inian Dec 07 '16 at 19:35
  • The output is continuous, and would eventually fill the disk if it was all saved. I don't understand why `| head -n 200 >/jumbo/program/log` will not actually capture the output? – Nikki Locke Dec 09 '16 at 10:58

0 Answers0