Wednesday, April 08, 2015

Add the server/service automatic startup scripts to run level during unix/linux OS reboot

This blog will guide you to add a server or service start-up script to run at start up and shutdown of Linux OS.(Same can be used for Solaris/Unix)

Step 1: Note down the command that you use to start the service.

Step 2: Prepare a script in the following format.

#/bin/bash
# chkconfig: 345 80 01  -- will explain y to use this in step 4 --
# description: App Server Startup/Shutdown script

case $1 in
start)

Script_path="/app/home/bin/path"

 if [ -f $Script_path/service_start.sh ]; then              //checks if the file exists in the directory        
  echo $"Starting Services"
  su - serviceid "-c nohup $Script_path/service_start.sh &"     //if file is present will run the command
 fi
 ;;
stop)
 if [ -f $Script_path/service_stop.sh ]; then
   echo $"Stopping Services"
   su - serviceid "-c nohup $Script_path/service_stop.sh &"
 fi
 ;;
*)
echo $"Usage: $0 {start|stop}"
//if start and stop is not passed a argument, Error will be displayed and script will exit.
exit 1
;;

Step 3: Save the script as Zscript (Z alphabet is added to ensure that the script runs at the end, You can choose any alphabet based on your priority). Give the execute permissions to the script. Place the script in /etc/init.d.

Step 4: Remember the "chkconfig: 345 80 01" added in the commented initial lines of the script? 

--> The "345" numbers indicate the run levels. 
--> "80" indicates the start priority with which the script has to run, for example a script with 79 priority will run before the script with 80 priority. 99 will be the highest priority that can be assigned to any script to run at the end.
--> "01"indicates the stop priority. It will stop first when compared to the other scripts with 02 as priority.

Step 5: Now to add this script in the desired run levels, Run the following command.

chkconfig --add Zscript

This will add the script, ie, create a softlinks for the choosen run levels. Ex : 345, were choosen in the scripts. So the script will be added as a soft link with Zscript name(80 is the priority) to /etc/init.d in /etc/rc3.d, /etc/rc4.d, /etc/rc5.d.

/etc/rc0.d -> K01Zscript
/etc/rc3.d -> S99Zscript
/etc/rc4.d -> S99Zscript
/etc/rc5.d -> S99Zscript

Once you add the Zscript to run levels, You can recheck the output using the following command.

chkconfig --list Zscript // it will give a o/p similar to following screenshot.


Step 6: To test the script now. you can be in anypath and run.

service Zscript start         //To check if the script runs at the startup of the server
service Zscript stop         // To check if the script runs at the shutdown of the server

Incase of any issues, You can comment in the comments section.

0 comments:

Post a Comment