racaraca69
racaraca69

Reputation: 13

Bash script conditional, else not working

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?

Upvotes: 1

Views: 64

Answers (2)

user1934428
user1934428

Reputation: 22225

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
  

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409146

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

Upvotes: 3

Related Questions