Marko
Marko

Reputation: 417

How to assign the output of a function to a variable in bash?

This has been already discussed, but I have a more different problem: I have a function that needs to be called with $@ as parameter.

If I put var=$(function $@) I just receive errors for every line where the function actions.

Meanwhile I used a workaroud:

  1. I called the function first: function $@
  2. Then I stored into the variable the result from the function: var=$?

But this works just if the function return is "succes" or "fail". Any thoughts?

Code:

function()
{
    if [ $1 -gt $x ]
    then
        return 0
    fi

    if [ $1 -eq $x ]
    then
        return 1
    fi

    if [ $1 -lt $x ]
    then
        return 2
    fi
}

I want to store in my variable 0 , 1 or 2. For this:

menu ()
{
    if [ $# -gt 5 ] || [ $# -lt 1 ]
    then
        echo "Error! Script is: " $0
        return
    fi

    echo "Insert reference number: "
    read x

    while [ $# -gt 0 ]
    do
        rez=$(function $@)

        if [ $rez -eq 0 ]
        then
            echo "Nr >!" $1
        fi

        if [ $rez -eq 1 ]
        then
            echo "Nr =!" $1
        fi

        if [ $rez -eq 2 ]
        then
            echo "Nr <!" $1
        fi
        shift
    done
}

Upvotes: 1

Views: 2833

Answers (1)

Geoff Nixon
Geoff Nixon

Reputation: 4994

  1. Maybe use elifs so that you don't receive multiple values that are returned (also a case statement might be a better solution).

  2. var=$(function $@ >/dev/null 2>&1; echo $?) should do what you want, I believe?

Upvotes: 2

Related Questions