Warm tip: This article is reproduced from stackoverflow.com, please click
bash linux shell sh embedded-linux

Pass output logs from a program into a function and store the return code in a variable at the same

发布于 2020-03-27 10:25:39

I have a shell script which has a function to Log statements. SomeProgram is another program which is run from my shell script and the logs from it are passed into the function LogToFile.

#!/bin/sh

LogToFile() {
    [[ ! -t 0 ]] && while read line; do echo "$line" >> $MY_LOG_FILE; done
    for arg; do echo "$arg" >> $MY_LOG_FILE; done
}

SomeProgram | LogToFile

Question:
All is good until here. But I have been trying to get the return code from SomeProgram and store it in a variable. How can I do that without loosing the functionality of logs from SomeProgram going into my LogToFile function. I tried the following options but in vain.

RETVAL=SomeProgram | LogToFile
RETVAL=(SomeProgram) | LogToFile
RETVAL=(SomeProgram | LogToFile)

Is it possible to pass the output of a program to a function parameter and collect the return value in another variable at the same time?

Questioner
AdeleGoldberg
Viewed
99
AdeleGoldberg 2019-07-04 15:30

I figured it out eventually. PIPESTATUS is the tool to use here.

Following is the way I can use it to get the return code of SomeProgram into RETVAL for example.

SomeProgram | LogToFile
RETVAL=${PIPESTATUS[0]}

Above is the way of getting the output of the program on the left of the pipe. PIPESTATUS is an array which contains the return codes of all the programs run adjacent to the pipe commands.

PIPESTATUS[1] could give the output of the LogToFile for example if LogToFile was a program.