help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

reading from external command


From: Peng Yu
Subject: reading from external command
Date: Tue, 29 Mar 2022 13:35:20 -0500

The following pattern is commonly seen, when one wants to read some
input and do something with the data taken in.

while read -r x; do
  results+=("$x") # somecode to change a variable that will be used
after the while-loop
done < <(
  builtin printf '%s\n' a b c # some command to generate input.
  # may be a pipeline line.
)
# do processing of results

The problem is that the exit status of the code in <() is not
accessible in the bash code anymore.

I may use a tempfile to save the result so that I can get the exit
status. But I prefer to avoid a file if possible.

builtin printf '%s\n' a b c > tempfile # exit status can be obtained here.

while read -r x; do
  results+=("$x")
done < tempfile

A pipeline may be used in this way to obtain the status of the command
generating the data via PIPESTATUS. But this way of coding will result
in nested pipelines when there are multiple input data sources. Also,
when there is error in the code generating the data fails, the
while-loop part will not know it.

builtin printf '%s\n' a b c | {
while read -r x; do
  results+=("$x")
done
# do processing of results here.
}

Is there a more elegant and efficient way to solve this problem
without having to use a tempfile?

-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]