Capturing number of lines of output and return code at the same time
I am writing a bash script that is called by a program (lets foo call it) that returns some output and gives a return code. I care about both the return code of the program and the number of lines to print (but not the output itself). Since the program involves fetching data over the Internet, I would prefer not to require it twice (in particular, it can cause problems unless one of the two requests is executed due to a transient network problem or something similar). The best script I can think of to capture both the number of output lines and the return code is the following. Is there something more elegant?
#!/bin/bash
line=$(foo | wc -l; echo ${PIPESTATUS[0]})
line=$(echo line | tr '\n' ' ')
lineCount=$(echo line | awk '{ print $1}')
returnCode=$(echo line | awk '{ print $2}')
For example:
set -o pipefail
lineCount=$(foo | wc -l)
returnCode=$?
This assumes it wc
never fails or you will get an exit status wc
.
Another way that doesn't depend on this assumption:
set +o pipefail
lineCount=$(foo | wc -l ; exit "${PIPESTATUS[0]}")
returnCode=$?
Eleganter but still awkward:
{ read lineCount; read returnCode; } < <(foo | wc -l; echo ${PIPESTATUS[0]})
If you don't expect the result to be huge, I would just grab it and then work with it:
output=$(foo)
returnCode=$?
lineCount=$(wc -l <<< "$output")