Sunday, 5 June 2016

How to check prerequisite in linux bash script?

Check the user is root or not?

if [ "$(whoami)" != 'root' ]; then
        echo "You have no permission to run $0 as non-root user."
        exit 1
fi

Check the OS?

OS=`cat /etc/issue |head -n 1 |awk '{ print $1 }'`
if [ $OS != "Ubuntu" ]; then
          echo "OS Architecture Not Supported...!"
       exit 1
fi

Check the VCPU' s?

vcpu=$(lscpu | grep "^CPU(s):.*$"|awk '{print $2}')
if [ $vcpu -lt 2 ];then
        echo "Minimum 2 vcpu's are Required...!"
        exit 1
fi


Check the Total Memory/RAM?

TotalMemory=$(grep MemTotal /proc/meminfo | awk '{print $2}')

if [ $TotalMemory -lt 8113442 ];then
        echo "Insuffiecient Memory 'Total RAM Should be 8G'"
        exit 1
fi

<<'COMMENT'
Total Memory        -  8G/100%  -   8388608KB
Operational Memory  -  .30%     -   25165.824KB
Remaining           -  99.7%    -   8363442.176
Required            -  6G/100%  -   6291456KB
COMMENT

Check the Available Memory/RAM?

FreeMemory=$(grep MemFree: /proc/meminfo |awk '{print $2}')
if [ $FreeMemory -lt 6291456 ];then
       echo "Insuffiecient Memory 'Require 6G Free Memory'"
       exit 1
fi

Check the any other installation' s are in progress?

if lsof /var/lib/apt/lists/lock >>/dev/null 2>&1 ;then
                echo "/var/lib/apt/lists/lock  locked"
                exit 1
fi

if lsof /var/lib/dpkg/lock >>/dev/null 2>&1 ;then
                echo "/var/lib/dpkg/lock  locked"
                exit 1
fi

Check the availability of Port?

nc -z 127.0.0.1 80;

if test "$?" -eq "0"  #if port 80 is in Listening mode
then
        echo "Port 80 is not available."
        exit 1
fi


Note: Tested under Ubuntu 12.x& 14.x

How to repair the MongoDB with bash script?


repair_and_restart_mongod(){

  if [ -f /etc/default/mongodb ]; then . /etc/default/mongodb; fi

  ENABLE_MONGODB="yes"
  if [ "x$ENABLE_MONGODB" = "xyes" ]; then
        if [ -f $MONGODB_HOME/mongod.lock ]; then
                rm $MONGODB_HOME/mongod.lock >> /dev/null
                sudo -u mongodb /usr/bin/mongod --config /etc/mongodb.conf --repair >> /dev/null
        fi
        #exec start-stop-daemon --start --quiet --chuid mongodb --exec  /usr/bin/mongod -- --config /etc/mongodb.conf
        service mongodb start >> /dev/null  2>&1
  fi
}

Tested under Ubuntu Server 12.x& 14.x