I am reviewing best practice with if statements. Below in example A I include the entire code to be run and ensure it remains within the if statement. While for example B the code to be executed resides outside the if statement.
From my understanding of Best practice on if/return, example A appears to be best practice.
Example A
#!/bin/bash
if [ `whoami` != 'root' ]
then
echo "MUST be ROOT!"
exit
else
ifconfig -a | sed 's/[ \t].*//;/^\(lo:\|\)$/d'
read -p "Enter interface: " int
mac=$(macchanger $int | grep 'Permanent MAC:' | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
ifconfig $int down
iwconfig $int mode manage
macchanger $int $mac
ifconfig $int up
echo "$int in stock configuration with MAC: $mac"
echo "Connect to a Wi-Fi network and run 'ping 1.1.1.1'"
sleep 2 && cinnamon-settings network &
fi
Example B
#!/bin/bash
if [ `whoami` != 'root' ]
then
echo "MUST be ROOT!"
exit
fi
ifconfig -a | sed 's/[ \t].*//;/^\(lo:\|\)$/d'
read -p "Enter interface: " int
mac=$(macchanger $int | grep 'Permanent MAC:' | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
ifconfig $int down
iwconfig $int mode manage
macchanger $int $mac
ifconfig $int up
echo "$int in stock configuration with MAC: $mac"
echo "Connect to a Wi-Fi network and run 'ping 1.1.1.1'"
sleep 2 && cinnamon-settings network &
I can foresee a potential example C, which would include structure:
if [ `whoami` != 'root' ]
then
echo "MUST be ROOT!"
exit
if [whoami' == 'root' ]
then
...
fi
However, this seems like creating an extra unnecessary condition, which uses additional resources. So, I will disregard example C.