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

Jimen Ching jching at flex.com
Thu Apr 15 15:58:19 EST 2004


On Thu, 15 Apr 2004, Riccarda Cassini wrote:
>My initial attempt to achieve the same effect in shell syntax was:
>
>  myfunc ()
>  {
>    local arg=$1
>    return "arg was: $arg"
>  }
>
>  par=test
>  var=myfunc($par)

A few corrections:

1.  The return command takes an integer.  So you can never 'return' a
string.  So the correct way to assign a string from a function is to use
an 'echo' like you found out.

2.  Calling a function is done with:

	func var1 var2 var3

There are no parentheses.

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 '$?'.

Hope this helps.

--jc
-- 
Jimen Ching (WH6BRR)      jching at flex.com     wh6brr at uhm.ampr.org


More information about the Programming mailing list