Philippe
Philippe

Reputation: 26707

Why the ERR trap get triggerred in bash from "echo <(cat <<EOF"

I have this script (test.sh) :

#!/bin/bash
  
set -o errtrace

trap 'echo $BASH_VERSION >&2' ERR

echo <(cat<<EOF
Hello world
EOF
)

Running it, I get :

~/tmp$ bash test.sh
/dev/fd/63
~/tmp$ 5.0.18(1)-release

Two questions :

  1. Why ERR trap get triggerred ?

  2. Why 5.0.18(1)-release is after next prompt, not before it

Upvotes: 1

Views: 147

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295649

Your copy of cat exits with a nonzero exit status because it's not able to write its output to stdout (since nothing in your code running in the parent shell actually reads from /dev/fd/63). The subshell spawned to run that copy of cat thus registers an error. As errtrace causes your ERR handler to be used in subshells and other contexts, this thus causes the process substitution's subshell to invoke the handler.

Because this process substitution is running in a subshell, it's asynchronous from the rest of your script; and cat is only given an error after the echo has exited (since it's only at that time that the read end of the FIFO is closed, and thus cat's attempts to write result in a SIGPIPE).

Upvotes: 6

Related Questions