0

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
1

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.