Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exit code from subshell through the pipes

How can I get exit code of wget from the subshell process?

So, main problem is that $? is equal 0. Where can $?=8 be founded?

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "$?"
0

It works without tee, actually.

$> OUT=$( wget -q "http://budueba.com/net" ); echo "$?"
8

But ${PIPESTATUS} array (I'm not sure it's related to that case) also does not contain that value.

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "${PIPESTATUS[1]}"    

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

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "${PIPESTATUS[-1]}"
0

So, my question is - how can I get wget's exit code through tee and subshell?

If it could be helpful, my bash version is 4.2.20.

like image 402
ДМИТРИЙ МАЛИКОВ Avatar asked Feb 14 '12 13:02

ДМИТРИЙ МАЛИКОВ


2 Answers

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=$? # safe exit code for later
  echo "$OUT" | tee -a "file.txt"
like image 97
Christian.K Avatar answered Sep 27 '22 18:09

Christian.K


Beware of this when using local variables:

local OUT=$(command; exit 1)
echo $? # 0

OUT=$(command; exit 1)
echo $? # 1
like image 45
Mrskman Avatar answered Sep 27 '22 19:09

Mrskman