Sunday, 29 January 2017

Bash Shell Script Template Guide - Part (1/2)

Hi Guys,

Want to write a bash script and don;t know the right structure ? This could help you to frame your script in standard way.  It's not exactly what it should be like but somewhat more appropriate way which makes it easy to use, more accurate, enhance readability,  and makes it look nice :)


  • The very first thing it is supposed to have 'shebang' 

          #/bin/bash 

⇉  Tips: Better to use #!/bin/env bash instead
  
  •  Next you can include script title,description,author,version etc.                                             
           # title                 : Myscript
           # description      : Blowing up the servers

           #
           # author             : Mahendra Shrivastava
           # approval          : John Do
           # date                 : 20170130
           # version            : 1.0.2

  • Display Usage  - It's better to have a usage display, defining how your script is supposed to be executed, how many 'arguments' it needs and if it has any dependencies on other file or programs etc. 
          usage()
         {
         cat << EOF

         usage: sh $0 options

         This script requires user file to pass
         eg. sh $0 -f /<Path-to-file>/User-details

         OPTIONS:
                  -f [ master file ]  File containing user details

                  -h Help

         EOF
         }
         null=''"

        if [ "$1" = $null ] then
            usage; exit ; fi



⇉Tips: If you are familiar  with 'getopts', include it to have more accuracy.  

  •  Path & Definitions    - Set Environment PATH and all  required definitions  

           ## Path

           PATH=$PATH:/usr/local/bin:/usr/bin; export PATH

           ## Definitions

          TIME=`date +"%Y-%m-%d_%T"`
          CMD_PWD=$(pwd)
          BACKUP=$CMD_PWD/backup
          LOG="/var/log/script.log"
      

          ## Hosts Details

          CONFIG_HOST='xyz1.host.com'