[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 136
  • Last Modified:

Interpreting $? output in bash shell

Hello, I am running a command using pipe, say

echo stats | nc hostname.com 1001
echo $?

Open in new window


and then I am getting the output of $? as 0. so here $? is depends on which command? echo or nc?? for getting $? 0 does both command needs to be executed successfully or either of nc or echo would do? how does $? gets evaluated in piping. Thanks!
0
beer9
Asked:
beer9
2 Solutions
 
Garry GlendownConsulting and Network/Security SpecialistCommented:
At least in Bash, the last command is relevant for the return value ... for example:

dustpuppy:~ # ls a
/bin/ls: a: No such file or directory
dustpuppy:~ # echo $?
1
dustpuppy:~ # ls a | cat
/bin/ls: a: No such file or directory
dustpuppy:~ # echo $?
0

Open in new window

The pipe itself does not evaluate any result codes, but only makes sure the actual stdio stuff is done ...
0
 
TintinCommented:
$? is always the status of the last command, so in your case it is the 'nc' command.

If you want to get the status of a command in a pipe (from memory, only supported by bash), you can inspect the PIPESTATUS array.

For example, if you do

ls | foobar | wc

Open in new window


$? will contain 0 (exit status of wc)

${PIPESTATUS[1]}  will contain value >0  (exit status of foobar)





0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now