Bash Scripting

Bash Scripting

ยท

6 min read

Hello every one Iam Goutham and in this article I would like to explain what is bash scripting in beginner terms as a part of DevOps.

Bash

Bash (Bourne Again Shell) is just an interpreter which is used to execute the statements that you write on the terminal.

To know which shell your Linux distro is using type $SHELL most Linux distros use bash as there default shell.

So instead of writing many commands one after the other on the terminal we place all commands in one file which ends with the .sh extension and we run the file and all commands run one after the other.

First Bash Script

First, let's create a file bashpractice.sh and we try to open the file using the Vim editor.

touch bashpractice.sh
vim bashpractice.sh

Now one editor will be opened and press i to edit file and write #!/bin/bash #! is called shebang and by /bin/bash we tell operating system to use bash shell (location of bash ) to execute the script file. echo editor opened and press esc and colon x! to save and come out from the editor.

To run the file type bash bashpractice.sh because by default we don't have permissions to execurte the file let's change permissions to execute the file.

sudo chmod 700 bashpractice.sh

By this we are giving read + write + execute permissions for user and no permissions for group and others.

Variables

Just like in any other programming language how variables are present in bash also we have variables.

#!/bin/bash

myvariable=bashscripting
echo $myvariable # to print variable we have to use $ before variable name.
## This is how we use comments in bash

Reading from the terminal

#!/bin/bash
read x

When we execute the script scree

Positional Arguments

While executing the script file we can even pass some arguments and we can collect them in script file by using $ symbol.

This is how script file looks like.

#!/bin/bash
echo $1 and $2

In the terminal we run the file In this way

./bashpractice Hello welcome # output is Hello and welcome

Hello is the first argument and welcome is the second by using $1 ,$2 we can collect them in a script file from the terminal.

Output and Input Redirection

We pass the output of one command to other file using > operator

echo "Hello World" > bashpractice.sh

Now entire text in bash practice will be replaced with Hello world If we want to append then

echo "Hello again" >> bashpractice.sh

Now Hello again will be appended to Hello world in bashpractice file.

Using | command we can redirect output of one command to other command.

ls -l | grep bash output of the ls -l command was redirected to grep command using | and grep command filters all the lines containing bash in it.

We can send file as an input to other commands like this

cat << EOF
Hello world 
EOF

If/Elif/Else

In bash also we have if else statements and we write like this

#!/bin/bash
var="hello"
if [ $var == hello ];  ## We can use  [] or () after if, spaces are must
  ## if you use () hello must be put in  quotes 
 then
echo "$var world"
elif ( $var ==  "helo" ) ;
then  
echo $var world
fi

We use (( )) syntax to perform arithmetic operations.

For example :

#!/bin/bash
if (( $1 < $2 ));
then 
echo  $2 is greater than $1
else 
echo  $1 is greater than $2
fi

This script file takes 2 positional arguments and prints which one is greater.

Bash script to find whether a given number is odd or even.

#!/bin/bash
if (( $1%2 )) ; ## Same if statement can also be wriiten as
# if [ $(( $1%2 )) == 0] both are same ;
then $1 is even
else 
echo $1 is odd
fi

Break down of that If statement

I exactly don't know in which format that expression returns 0 if the number is odd. To perform arithmetic operations we have to use (()) syntax and to convert to its original value we have to use $ in front of it [] syntax is used to check for true or false condition.

Alternatively, we can use expr to perform arithmetic operations.

#!/bin/bash
if [ `expr $1 % 2` == 0 ] ;
then
echo even 
else
echo odd
fi

Loops

We can declare arrays in bash like this

array=(1 2 3 4 5)
echo ${arr[@]} # To print all elements * can also be used
#!/bin/bash
#For Loop
for i in $array ;
do 
echo $i
done
# Traditional For loop
for (( i=0;i<5;++i ));
do 
echo ${array[$i]}
done
# Range based Loop
for i in {1..10};
do 
echo $i  ## After completion of this Loop 1 to 10 numbers will be printed
done
# While 
i=0
while (( $i < 5 ));
do 
echo ${array[$i]};
(( i++ ))
done
## Do while 
i=0
do
echo ${array[$i]};
(( i++ ))
done
while (( $i < 5))

Debugging

If the script file contains many commands then it becomes difficult for the user to read which is the out put of which command.

So set -x command is used to distinguish between the output of previous one and next one.

set -x
ls
touch x.txt
for (( i=0;i<2;++i ));
do 
echo ${array[$i]}
done

When we run this script we get Each command is also printed by which we can get an idea of what exactly happened while executing the script.

++ ls
0  45  bash.sh  c  n.txt  snap  x.txt
++ touch x.txt
++ (( i=0 ))
++ (( i<5 ))
++ echo 1
1
++ (( ++i  ))
++ (( i<5 ))

So when we want to stop the execution of script if an error is present.

Then set -e command has to be used

set -e #  If we don't put this one even though script has error it executes 
 # successfully.
ls
touch x.txt
wedwehduzuhu # statement that cause error
echo hello

So when the script has many commands and it contains a small error we can't see that one so this command is used to stop executing when there is an error.

awk

This command is used to fetch specific word from the line in the output of the script.

ls -l | awk -F " " '{print $1}'

awk command accepts output from ls-l command as there are many unnecessary words like owner , group ,date etc in this command if we are only interested in printing 1st one word or 2nd word we can easily print them using this command.

-F is field seperator . In the above command awk treats " " as a separator.

So That's it. If you found this blog interesting please like. If you found anything I missed or written wrong then please let me know.

Thanks for reading ๐ŸŽ‰๐ŸŽ‰.

ย