Returning value from a function in shell script [duplicate]
The "return value" of a function as you used it is stdout."return" will set exit status ($?), which you probably have no use for."test" is probably a bad choice of name, since it's taken (qv. man test
).So:
$ Test() { expr $1 + 10000; }$ var=$(Test 10)$ echo $var10010
if all you wish to do is add 10000 to your input, then a function is overkill. for this, wouldnt this work?
your_arg=10var=$(( ${your_arg}+10000 ))echo $var
There are some issues in your code.
#!/bin/bash
It works but it is no good idea to define a function called test
, because test
is a standard Unix program.
test(){
Write debug output to standard error (&2) instead of standard output (&1). Standard output is used to return data.
echo "$1" >&2
Declare variables in functions with local
to avoid side effects.
local c=$(expr "$1" + "10000")
Use echo
instead of return
to return strings. return
can return only integers.
echo "$c"}var=$(test 10)
If unsure always quote arguments.
echo "$var" >&2