3

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}
Yogu
1471 silver badge8 bronze badges
asked May 4, 2014 at 9:52

3 Answers 3

4

The exit code is contained in $?:

fun 2
a=$?
answered May 4, 2014 at 9:54
1

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.

answered May 4, 2014 at 10:11
1
  • 1
    Welcome 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. Commented May 4, 2014 at 10:59
0
#!/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 "--------------------"

nice bash tutorial, link points to functions invocation

answered May 4, 2014 at 11:02
1

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.