Feb 222012

It’s funny how through small daily tasks sometimes it happen to find new features or commands that you do not knew not, and today this thing happened to me.
In particular, I had to do something trivial on the shell of a server, run : command1 | tail-n 2 i use tail to keep, from a significant long output, only the last 2 lines which then i use in another function, but beyond this, I needed to understand if command1 was terminated with an exit code of 0 or if the code was not 0 which number it was.

A simple:

comando1 | tail -n 2 
if [ $? -ne 0 ]
		echo "comando1 fallito."

Does not work because the exit code comes from the command tail, which in my case is always 0.
So I Googled a bit and found more than a solution for this simple problem.

Ok, let’s start with the solution i’ve used, for bash:

1) If you have cmd1 | cmd2 | cmd3
In Bash the exit codes are provided in the PIPESTATUS special array. cmd1 exit code is in ${PIPESTATUS[0]}, cmd3 exit code in ${PIPESTATUS[2]}, so that $? is always the same as ${PIPESTATUS: -1}. But is really so simple ?
Yes once you know this, getting the right exit code is trivial !

So my code has become:

command1 | tail -n 2
if [ ${PIPESTATUS[0]} -ne 0]
echo “command1 failed.”

2) You can use a similar solution also for zsh also in this shell the exit codes are provided in the pipestatus special array. cmd1 exit code is in $pipestatus[1], cmd3 exit code in $pipestatus[3], so that $? is always the same as $pipestatus[-1].

So, as you can see this is exactly the same solution used in bash.

3) For Ksh and probably other bash like shell, you need to use a trick to pass the exit codes to the main shell. You can do it using a pipe(2). Instead of running “cmd1”, you run “cmd1; echo $?” and make sure $? makes it way to the shell.

This is the most complex example, and i suggest to take a look at the I/O redirection in Unix/Linux if you have some doubt.

#! /usr/bin/ksh
exec 4>&1
tail -n 2 >&4 |&
exec >&p
exec >&- >&4
if [ ${exitcode} -ne 0]
  echo "command1 failed."

So in conclusion, luckily for me in Bash there is that special array !
And many thanks to the forum unix.com for all the useful information available.

Popular Posts:

Flattr this!

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>