Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture number of lines of output and return code simultaneously

Tags:

bash

I am writing a bash script that will call a program (lets call it foo) that returns some output, and gives a return code. I care about both the return code of program and the number of lines output (but not the output itself). Because the program involves retrieving data over the internet, I would prefer not to have to invoke it twice (in particular, this could cause problems if only one of the two invokations fail due to a transient network issue or something similar). The best script I can come up with to capture both the number of output lines and 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}')
like image 770
orangejulius Avatar asked Oct 21 '25 16:10

orangejulius


1 Answers

For example:

set -o pipefail
lineCount=$(foo | wc -l)
returnCode=$?

This assumes that wc never fails, otherwise you get wc's exit status.

Another way that doesn't depend on this assumption:

set +o pipefail
lineCount=$(foo | wc -l ; exit "${PIPESTATUS[0]}")
returnCode=$?
like image 194
Philipp Avatar answered Oct 23 '25 08:10

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!