[prog] Returning a string from a function, in bash

Conor Daly c.daly at met.ie
Fri Apr 16 14:27:51 EST 2004


On Fri, Apr 16, 2004 at 02:51:12PM +0200 or thereabouts, Riccarda Cassini wrote:
> Hi Conor,
> 
> > myfunc()
> > {
> >   echo `command and result`
> >   local result=$?
> >   if [ $result -eq 0 ]; then  # you can also test on $? itself but only
> once
> >     return 0
> >   fi
> >   return 1
> > }
> 
> is there a specific reason for explicitly returning 0 and 1, rather
> than just writing "return $?".  I would've thought that if you test
> for "-ne 0" on the return code afterwards, the net effect would be
> the same (at least if there's no other code in between).  Is there
> some subtle issue with "return $?" - which, as I understand it, would
> sort of assign $? to itself? (serious question, not just wanting to
> be clever).

It depends on what else you are going to do in an error situation.  If you
were to run 'grep blah file' so as to return some line, you might want to
return "not found" rather than "" if there was no match.  To do this you
might do:

myfunc()
{
  OUTPUT=`grep blah file`
  result=$?
  if [ $result -eq 0 ]; then
    echo $OUTPUT
    return 0
  else
    echo "not found"
    return 1
  fi
}

The ways of $? are subtle and likely to bite you unless you know what you're
doing[0].  Essentially, $? contains the return value of the last command
executed.  It's generally useful practice to assign $? to a variable and then to do
conditionals based on the variable.  I have a suspicion that my:
> >   echo `command and result`
> >   local result=$?

may itself be flawed since it may be the return code from 'echo' that ends
up in $result rather than that from `command...`.  If you want the return
value of a command, run the command, optionally assign the output to a
variable, and capture the return value.  Only then should you start doing
fancy stuff with the output.

Conor (clear as mud??)

[0] This should not be interpreted as me claiming to know what _I'm_
    doing...  :-)
-- 
Conor Daly,                   Please avoid sending me 
Met Eireann, Glasnevin Hill,  Word or PowerPoint attachments.
Dublin 9, Ireland             http://www.fsf.org/philosophy/no-word-attachments.html
Ph +3531 8064276 Fax +3531 8064247


**********************************************************************
This e-mail and any files transmitted with it are confidential 
and intended solely for the addressee. If you have received
this email in error please notify the sender.
This e-mail message has also been scanned for the
presence of computer viruses.
**********************************************************************



More information about the Programming mailing list