Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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}
share|improve this question

3 Answers 3

up vote 4 down vote accepted

The exit code is contained in $?:

fun 2
a=$?
share|improve this answer

you may have a look at the following question: http://stackoverflow.com/questions/8742783/returning-value-from-called-function-in-shell-script with a long and well explained answer. Regards.

share|improve this answer
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. –  terdon May 4 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 "--------------------"

nice bash tutorial, link points to functions invocation

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.