Shell Scripting

Disadvantages of shell script

Not idempotent    -write custom code to make it idempotent

Error handling    -- we need to write code to check the errors

Homogeneous     --only works in specific distro

Not scalable when to many servers

syntax is not easy to understand


Still shell scripting is powerful when we have minimum number of servers

Configuration management : take plain server without anything installed

install app runtime and few packages

create users and folders, download code, install dependencies, creating systemctl services, 

copying config files

we can use Shell scripting to do configuration management in few servers.

So to do Configuration management in many servers we choose Ansible instead of shell scripting


Shell is an interpreter that executes commands


Create a shell script and execute

 vi simple_script.sh

#! /bin/bash     --> is the first line in the script called shebang line 
# Author         --> Amruth
# comment     --> only first line '#' is not considered as comment, all other lines starts with '#' are                                         commnets
pwd
echo "welcome to script"
ls

Esc > :wq! --> to save the changes

=================================================================

In Any Language like java, .net, Python, shellscript etc, below 4 are the important concepts

  • Variables
  • Data types
  • Conditions
  • Loops
  • Functions

=================================================================

Developers code should be:    

  • Performance --> high should load fast.
  • DB --> must fetch the data fast.
  • Memory and system resources --> should consume less

In Scripting:

  • No DB
  • No need of super performance and system resources.

=================================================================

Variables:

Variable_name=Value    (No space between name,equal,value)

Variable in shellscript

Variables can be passed in three ways

    1. can declare int he script
    2. can pass as arguments
    3. can pass during runtime


#! /bin/bash
Person1=Ramesh
Person2=Suresh
echo "Hello $Person1, How are you"
echo "Hello $Person2, I am fine, How are you doing"

echo "${person1} I am doing good "


User should have Execute permission to run the script.

chmod a+x simple_script.sh --> it means give execute permissions to all.

sh simple_script.sh    -->to run the script

bash simpe_script.sh    --> to run the script file.

./simple_script.sh    --> another method to run the script file


Parameter passing in shellscript

simple_script.sh

#! /bin/bash
Person1=$1
Person2=$2
echo "Hello $Person1, How are you"
echo "Hello $Person2, I am fine, How are you doing"

echo "${person1} I am doing good "

    #bash simple_script.sh Ramesh Suresh


passing variable during runtime

simple_script.sh

#! /bin/bash
echo "please enter user name:"

read USERNAME

echo "please enter user password:"

read -s PASSWORD    --> Here '-s' is used to hide the text we enter during run time.

echo "username is $USERNAME"


To Automate the script use cron job

crontab -e    --> opens your user’s crontab file.

Add a line like 0 * * * * /path/to/myscript.sh   to run your script hourly.


git clone    --> to download the entire repository for the first time.

git pull    --> for any changes to download from the git hub repository


gir add. ; git commit -m "commit message"; git push origin main     (single line execution of all 3 commands)


Datatype

int, sting, Array, 

#! /bin/bash
#index starts from 0, size is 3 for below fruit array
FRUITS=("Apple","Mango","Guava")

echo "First fruit is ${FRUIT[0]}"

 echo "First fruit is ${FRUIT[@]}"    -->Here '@' means all



#! /bin/bash

DATE=$(date)

echo "date is $DATE"


Special variables

echo "gives all the arguments passed: $@"

echo "gives the count of the variables passed: $#"

echo " gives the current scriptname: $0"

echo "process id of the script executing now: $$"

echo "process id of the previous background process: $!"  (example : sleep 100 &)


$?    --> if it gives '0' previous command is success 'other then 0' then the previous command is not                         success


Conditions


if [ condition ]

then

    statement1

else

    statement2

fi


NUMBER=$1

if [ $NUMBER -gt 20 ]  --> Here -gt is greater than, -lt means less than, -eq is equal to, -ne is not equal                                                 to, -ge is greater than or equal to , -le is less than or equal to

then

    echo "given number: $NUMBER is greater than 20"

else

    echo "given number: $NUMBER is less than 20"

fi


To install git with sudo previliges

#! /bin/bash
USERID=$(id -u)
if [ USERID -ne 0 ]
    echo "please run the code with sudo user"
    exit 1                    --> to come out of the code execution
fi

dnf install git -y


#! /bin/bash
USERID=$(id -u)
if [ USERID -ne 0 ]
  then 
    echo "please run the code with sudo user"
    exit 1                    --> to come out of the code execution
fi
dnf list installed git 

       if  [ $? -ne 0 ]
            then 
                    echo "git is not installed, going to install it"
                    dnf install git -y
                        if [$? -ne 0]
                               echo "git installation failed.."
                                exit 1
                        else
                            echo "git installtion success"
                        fi
          else
               echo "git already installed"
           fi



Functions

Function_name()

{

}

---------------------------------


#! /bin/bash
USERID=$(id -u)

VALIDATE()
{
    if [$1 -ne 0]
        then 
                echo "$2 is failed"
                exit 1
     else
                echo "$2 is success"   
}

CHECK_ROOT()
{
    if [ $1 -ne 0 ]
      then 
        echo "please run the code with sudo user"
        exit 1                    --> to come out of the code execution
    fi
}


CHECEK_ROOT USERID                --> Function_call CHECK_ROOT 
dnf list installed git 


       if  [ $? -ne 0 ]
            then 
                    echo "git is not installed, going to install it"
                    dnf install git -y
                       VALIDATE $? installed git            --> Function_call VALIDATE
          else
               echo "git already installed"
          fi
dnf list installed mysql

if [$? -ne 0]
then 
        echo "Mysql is not installed, going to install now"
        dnf install mysql -y
    VALIDATE $? installed mysql
 else
       echo "mysql is already installed"
fi


Color

-e "\e[31m   "       here '-e' means enable      31m -->Red, 32m--> green, 33m--> yellow


echo hello world
echo -e "\e [31m hello world"

Loop
for i in 1 2 3 4 5 6 7 8 9 10
do
    echo $i
done
---------------------------------------
for i in {0..10}
do 
    echo $i
done
------------------------------------------

To install multiple softwares using loop

for package $@    --> here $@ means all arguements passed
do
dnf list installed $package
if  [ $? -ne 0 ]
then 
     echo "$package is not installed, going to install now"
        dnf install $package -y
    VALIDATE $? installed $package
 else
       echo "mysql is already installed"
fi
done

Run : sudo sh simple_script.sh git mysql nginx postfix

log
redirectors (>)

ls -l > output.txt --> by default it redirects only the success output.
lss > output.txt     --> it prints on screen, because the command fails
ls-l 1 > output        --> here '1' means success, writes to file
ls -l 2 > output.txt    --> here '2' means failure, no writes to file
ls -l & > output.txt    --> here '&' means all ie, success or failure , write to file.
 ls - lrt &>> output.txt    --> here '>>' is to append the date in file.


idempotency     --> if you run the script infinite times it should give the same result.


Deployment

Downtime notification
Stop the services
back up the existing version
remove the existing version
download the new version
start the server

Comments

Popular posts from this blog

Ansible