Raja G
Raja G

Reputation: 6633

bash: function returning output instead of output status

I have a small bash script as below

function getUptime() {

    uptime 2>/dev/null
    return "$?"
}

resultReceived=$(getUptime)
echo "Result: $resultReceived"

And when I execute the script, instead of 0 I am getting uptime command output. Where I am doing the mistake. Please help.

Debug Output

 tmp bash -x testingscript.sh
++ getUptime
++ uptime
++ return 0
+ resultReceived='11:47  up 3 days, 19:24, 7 users, load averages: 1.88 1.78 2.04'
+ echo 'Result: 11:47  up 3 days, 19:24, 7 users, load averages: 1.88 1.78 2.04'
Result: 11:47  up 3 days, 19:24, 7 users, load averages: 1.88 1.78 2.04

Upvotes: 0

Views: 31

Answers (1)

jeb
jeb

Reputation: 82307

You mixed the exit status and the output.
With $(getUptime) you get the output of your function, not the exit status.

You could change your function, but then the name will not match it's functionality.

function getUptime() {

    uptime >/dev/null 2>/dev/null
    echo "$?"
}

I suppose it's better not to change the function, instead change the code at:

resultReceived=$(getUptime)
exitstatus=$?
echo "Result: $resultReceived, exitstatus: $exitstatus"

Upvotes: 1

Related Questions