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}
4

The exit code is contained in $?:

fun 2
a=$?
| improve this answer | |
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.

| 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 '14 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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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