How can I use the integer value returned by a function in shell script that takes some arguments as input?
I am using the following code:
fun()
{
echo "hello ${1}"
return 1
}
a= fun 2
echo $a
I am not sure how should I call this function. I tried the methods below, bot none of them seems to work:
a= fun 2
a=`fun 2`
a=${fun 2}
3 Answers 3
The exit code is contained in $?
:
fun 2
a=$?
you may have a look at the following question: https://stackoverflow.com/questions/8742783/returning-value-from-called-function-in-shell-script with a long and well explained answer. Regards.
-
1Welcome to Unix & Linux Stack Exchange! While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.2014年05月04日 10:59:12 +00:00Commented May 4, 2014 at 10:59
#!/bin/bash
function producer_func()
{
echo "1"
echo "[ 1ドル ]"
echo "2"
echo "3"
}
function returner_func()
{
echo "output from returner_func"
return 1
}
#just print to stdout from function
producer_func "aa ww"
echo "--------------------"
#accumulate function output into variable
some_var=$(producer_func "bbb ccc")
echo -e "<$some_var>"
echo "--------------------"
#get returned value from function, may be integer only
returner_func
echo "returner_func returned $?"
echo "--------------------"
#accumulate output and get return value
some_other_var=`returner_func`
echo "<$some_other_var>"
echo "returner_func returned $?"
echo "--------------------"
-
1FYI, this uses a nonstandard function definition syntax.Wildcard– Wildcard2016年02月06日 07:14:39 +00:00Commented Feb 6, 2016 at 7:14