Get exit code from subshell through the pipes

By using $() you are (effectively) creating a subshell. Thus the PIPESTATUS instance you need to look at is only available inside your subshell (i.e. inside the $()), since environment variables do not propagate from child to parent processes.

You could do something like this:

  OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt"; exit ${PIPESTATUS[0]} );
  echo $? # prints exit code of wget.

You can achieve a similar behavior by using the following:

  OUT=$(wget -q "http://budueba.com/net")
  rc=$? # save exit code for later
  echo "$OUT" | tee -a "file.txt"

Leave a Comment