Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

collecting exit code on variable 2

Status
Not open for further replies.

yesornot

Technical User
Apr 15, 2015
7
PL

why red echo does not return '2' while green one does?

Code:
$ unset C
$ { ls missing 2>&1;C=$?; }
ls: 0653-341 The file missing does not exist.
$ [COLOR=#8AE234]echo $C[/color]
2
$ unset C
$ { ls missing 2>&1;C=$?; }|sed s/^/error:\ /g
error: ls: 0653-341 The file missing does not exist.
$ [COLOR=#EF2929]echo $C[/color]

$
 
Hi

Because the pipe forces the running of the list in a subshell :
Code:
[blue]master #[/blue] { ps; }
  PID TTY          TIME CMD
18232 pts/7    00:00:00 bash
18496 pts/7    00:00:00 ps

[blue]master #[/blue] { ps; } | cat
  PID TTY          TIME CMD
18232 pts/7    00:00:00 bash
18500 pts/7    00:00:00 bash
18501 pts/7    00:00:00 cat
18502 pts/7    00:00:00 ps

See ? Another [tt]bash[/tt] process appeared and the list will be executed by that one. That includes setting the C variable in that second [tt]bash[/tt]'s environment, which vanishes as soon the list's execution ends.

Regarding your code, I would rewrite it without trying to pass [tt]$?[/tt] through a variable, using [tt]PIPESTATUS[/tt] instead :
man bash said:
[pre]
PIPESTATUS
An array variable (see Arrays below) containing a list of exit
status values from the processes in the most-recently-executed
foreground pipeline (which may contain only a single command).[/pre]
Code:
[blue]master #[/blue] ls missing 2>&1 | sed s/^/error:\ /g
error: ls: cannot access missing: No such file or directory

[blue]master #[/blue] echo "${PIPESTATUS[0]}"
2

Feherke.
feherke.ga
 
thank you.

btw. in ksh93g+, which does not have PIPESTATUS I found another trick for getting exit code

Code:
$ ls missing 2>&1|sed s/^/error:\ /g
error: ls: 0653-341 The file missing does not exist.
$ echo $?
0
$ set -o pipefail
$ ls missing 2>&1|sed s/^/error:\ /g
error: ls: 0653-341 The file missing does not exist.
$ echo $?
2
$

in older ksh it is probably not such trivial.
maybe by doing/collecting exit code on output (echo $?) and processing it later
 
Hi

Doh. And [tt]pipefail[/tt] exists in Bash too. I never used it. That is a great trick, thanks.


Feherke.
feherke.ga
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top