Else IF Or Branching On Bash Scripting

This is the core of programming art, because we need to fully use if else statement or branching to examine one condition, if true the code will execute something or if false the code will do another examine process or just exit the code.
Programming is just as simple is this! but sometime will make us very overhead at this process :v

Here I will demonstrate simple if else on scripting.

First we will try without creating .sh file, we immediately type it out into terminal like this.
sysadmin@localhost:~$ echo $USER
sysadmin 

We found the hostname is sysadmin and we will make the system examine if the hostname is sysadmin then prin hi sysadmin.

sysadmin@localhost:~$ if [ $USER = 'sysadmin' ]
> then 
> echo 'hi sysadmin!'
> fi
hi sysadmin!

You now understand that is very simple and similar with other programming language. Now we try to create one file and put it a few condition like this.

#!/bin/bash
ARCHITECTURE=`uname -m` 
if [ $ARCHITECTURE = "i686" ] 
then     
        echo "The operating system is detected as 32bit"
fi
if [ $ARCHITECTURE = "x86_64" ]
then
        echo "The operating system is detected as 64bit"
fi

Actualy you can also do like this depend on your need. In the third example I try to examine morethan 2 condition and we can use elif there.
#!/bin/bash
ARCHITECTURE=`uname -m` 
if [ $ARCHITECTURE = "i686" ] 
then     
        echo "The operating system is detected as 32bit"

elif [ $ARCHITECTURE = "Itanium" ]
then
echo "The operating system is detected as Itanium"

elif [ $ARCHITECTURE = "x86_64" ]
then
        echo "The operating system is detected as 64bit"
else
echo "Other proc architecture"
fi

Actualy the output will be the same on both script since this script is examining proc architecture on the operating system and I run this script on the same PC so the output will be like this.
sysadmin@localhost:~$ ./proc.sh
The operating system is detected as 64bit

Hey don't forget to give executeable permission before run that script okay!

Tulis komentar anda... Conversion Conversion Emoticon Emoticon

Thanks for your comment