How to capture stderr in a variable and output stdout pipes through

I am trying to save the headers (from stderr) of the response in a variable and pass the body (from stdout) to grep.

Here is my current attempt:

{
  HEADERS=$(curl -vs $URL 2>&1 1>&3-)
  echo "$HEADERS"
} 3>&1 | grep "regex" >> filename
echo "$HEADERS"

When I run the script with bash -x script.sh, I see + HEADERS='...'the expected output, but I can’t access them from $HEADERSeither "$HEADERS"inside or outside the built-in group.

The body gains access to the pipeline as expected.

+4
source share
2 answers

As anubhava is correctly diagnosed , the problem is that you are installing HEADERSinto a subprocess, not the main process of your shell.

Bash , , , :

HEADERS=""
{ HEADERS=$(curl -vs "$URL" 2>&1 1>&3-); } 3> >(grep "regex" > file)
echo "$HEADERS"

grep . 3> >(…).

+2

HEADERS - , , , .

:

{ f=$(mktemp /tmp/curl.XXXXXX); curl -vs "$URL" 2>"$f" |
grep 'regex' >> filename; HEADERS="$(<$f)"; trap 'rm -f "$f"' EXIT;}

HEADERS , , mktemp.

+2

All Articles