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

Conor Daly c.daly at met.ie
Fri Apr 16 08:38:28 EST 2004


On Thu, Apr 15, 2004 at 03:58:19PM -1000 or thereabouts, Jimen Ching wrote:
> 
> 3.  To save the return value (an integer), you assign the result
> environment variable:
> 
> 	func var
> 	result=$?
> 
> This assignment must be done before any other command, because the next
> command will update '$?'.

This could be useful for making your function robust.  You don't want
something that echoes a multiline error message to make your main script
break so:

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
}

output=`myfunc arg`
result=$?
if [ $result -ne 0 ]; then
  echo "Call to myfunc() failed!"
fi

Now your main script can use the string in $output only if the function
succeeded...

Conor
-- 
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