I have a script that parses file names into an array using the following method taken from a Q&A on SO:
unset ARGS
ARGID="1"
while IFS= read -r -d $'\0' FILE; do
ARGS[ARGID++]="$FILE"
done < <(find "$@" -type f -name '*.txt' -print0)
This works great and handles all types of filename variations perfectly. Sometimes, however, I will pass a non-existing file to the script, e.g:
$ findscript.sh existingfolder nonexistingfolder
find: `nonexistingfile': No such file or directory
...
Under normal circumstances I would have the script capture the exit code with something like RET=$?
and use it to decide how to proceed. This does not seem to work with the process substitution above.
What's the correct procedure in cases like this? How can I capture the return code? Are there other more suitable ways to determine if something went wrong in the substituted process?
read -u
should work just as well. The example was meant to be generic and show how the output of the coprocess could be piped into another command. – Feuermurmel Aug 14 '18 at 12:38read -u
works but prints an error at the end of the loop:read: : invalid file descriptor specification
– Dima Korobskiy Jun 05 '20 at 18:50$LS
(which is$LS[0]
) is unset when the co-process exits (so it's not justLS_PID
). Add asleep 1
before the loop, and you will see (read: : invalid file descriptor specification
). Stay away fromcoproc
, it's a trap for the uninitiated. – ddekany May 24 '21 at 18:11coproc
once and regretted it. If a shell script requires me to use something likecoproc
, most of the time it's already one and a half headaches beyond the point where I should have rewritten it in e.g. Python. – Feuermurmel May 26 '21 at 06:14find
results. So switching to Python is maybe too much hassle, if the are alternatives. Like just accepting the risk of a failingfind
, or usingshopt -s lastpipe
and the intuitive pipe solution. – ddekany May 26 '21 at 11:11