1

Here is my script

#!/bin/bash

sudo pkexec ip link set can0 up type can bitrate 1000000
echo $?
result=$?

if [[ result -eq 0 ]]
then
  echo "Node will initialize"
else
  echo "Node will not initialize"
fi

It will just read the exit status of the above terminal command and will print out messages according to the condition. As I run the script, even the result is equal to 0 or 1 or 2, it will print "Node will initialize". What could be wrong?

2 Answers 2

3

Order matters!

With result=$? you get the result of the echo $? command.

Do the assignment first, and print the value of $result instead:

sudo pkexec ip link set can0 up type can bitrate 1000000
result=$?
echo $result
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!, I haven't thought of that. It is now working. Thanks again
1

UPDATE based on the comment by rowboat:

While -eq inside [[ ... ]] indeed also imposes numeric context and makes [[ result -eq 0 ]] feasible, arithmetic interpretation is easier to express by (( .... )). In this example, this would be

sudo pkexec ip link set can0 up type can bitrate 1000000
result=$?

if (( result == 0 ))
then
  echo "Node will initialize"
else
  echo "Node will not initialize, exit code: $result"
fi

Of course if pkexec only returns the exit codes 0 and 1, respectively if we don't want to differentiate between the various non-zero exit codes, we can write even easier

if sudo pkexec ip link set can0 up type can bitrate 1000000
then
  echo "Node will initialize"
else
  echo "Node will not initialize"
fi
  

8 Comments

I tried replacing -eq with == and it prints "Node will not initialize" even if the result is equal to 0 or 1. I guess -eq works fine by me but still thank you for your input. But what does -eq differ from ==??
@racaraca69 : Did you write the round parenthesis? Copy and paste the exact command you are using.
The [[ does do arithmetic evaluation e.g. bash -c '[[ 1+1 -eq 2 ]] && echo OK'
I agree that (()) is easier, but [[ \(a+b\)*c -le d ]] would work.
Interesting. I didn't know that bash allows expressions and implicit expansion of variables here too. Good to know!
|

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.