Search code examples
bashshellsubshell

Retrieve the first/last line of subshell stdout


If I have a subshell command:

output="$(runfoo)";

is there way to store only the last line of the output from runfoo into the variable output? Or perhaps only the first line?


Solution

  • Only stdout:

    output="$(runfoo | tail -n 1)"
    
    output="$(runfoo | head -n 1)"
    

    Stdout and stderr:

    output="$(runfoo 2>&1 | tail -n 1)"
    
    output="$(runfoo 2>&1 | head -n 1)"