Home > Back-end >  Bash script conditional, else not working
Bash script conditional, else not working

Time:09-01

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?

CodePudding user response:

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

CodePudding user response:

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
  
  • Related