Make bash script run as service in CentOS 6

Share this post to your friends !

WriteBash - Today I will show you how to make a bash script run as service in CentOS 6 (versions 6.x). Running a bash script as a service is very useful for you in case you want your script to run almost realtime.

Most of the time we use scripts that usually combine crontab to execute automatically. But with scripting as a service, you can do more than that.

Write your bash script

The first thing and of course, you need to write your program and in this case write your bash script.

In the example in this article, I will write a simple program to get the load average of the server every 1 second. This information is written to a text file and we can see the results continuously.

The content of the script is below:

#!/bin/bash
# Script author: Danie Pham
# Script site: https://www.writebash.com
# Script date: 16-01-2018
# Script ver: 1.0
# Demo bash script run as a service in CentOS 6
# Script use to get load average of server every 1 second

# Function get load average
f_get_average () {
    # This command will add time to each line
    date >> $FILE

    # This command will get load average and write to FILE
    uptime | awk -F'load average: ' '{print $2}' >> $FILE

    # Echo a line spacing
    echo "" >> $FILE
}

# Main function. You can call any functions as you want to this function
f_main () {
    # Define a text file
    FILE="/tmp/writebash_demo.txt"

    # We you a loop to run function f_get_average forever
    while true
    do
        # Call function
        f_get_average

        # Sleep 1 second
        sleep 1
    done
}
f_main

exit

You copy the above script to your machine and grant the executable to the script, for example, i name it is getload.sh.

chmod 700 /opt/getload.sh

You can download the script here.

After having your main program, how to do it can run as a service?

Make bash script run as service

Read how to make bash script run as a service in CentOS 7.

In this step, we first need to create an init file for your bash script. This init file is very important, it is the key to making your script run as service. If you want to find out more about the init file, you can read the CentOS documentation.

Create init file

You create the file /etc/init.d/getload and copy the content below into the file. Then you assign permissions to the newly created init file.

chmod +x /etc/init.d/getload

The complete init file is below:

#!/bin/bash
#
# /etc/init.d/getload
# Subsystem file for "getload" service
#
# chkconfig: 2345 95 05
# description: writebash demo getload service daemon
#
# processname: getload
# pidfile: /var/run/getload.pid

# source function library
. /etc/rc.d/init.d/functions

SERVICE=getload
PIDFILE=/var/run/$SERVICE.pid
LOGFILE=/var/log/$SERVICE.log
SCRIPT=/opt/$SERVICE.sh

start () {
    if [[ -f $PIDFILE ]] && kill -0 $(cat $PIDFILE); then
        echo "$SERVICE alrealdy running, pid=`cat $PIDFILE`"
    else
        echo "Starting $SERVICE ..."
        $SCRIPT >> $LOGFILE & echo $!>$PIDFILE
        echo "$SERVICE started !"
    fi
}

stop () {
    if [[ ! -f $PIDFILE ]] && kill -0 $(cat $PIDFILE); then
        echo "$SERVICE is not running"
    else
        echo "Stopping $SERVICE ..."
        kill -15 $(cat $PIDFILE)
        rm -f $PIDFILE
        echo "$SERVICE stopped !"
    fi
}

restart () {
    $0 stop
    $0 start
}

status () {
    if [[ -e $PIDFILE ]] && kill -0 $(cat $PIDFILE); then
        echo "$SERVICE is running, pid=`cat $PIDFILE`"
    else
        echo "$SERVICE is not running"
        exit 1
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0

I will explain to you in turn the parts of the init file, so you can customize to suit your program.

  1. The first part is the lines starting with #: this section declares the information about your service, if missing these lines, the operating system will not be able to understand your service generates. These lines are very important, especially the chkconfig line. Because this line allows you to use the chkconfig command in CentOS to make your script run automatically after reboot.
  2. The next 4 lines: declare the service name, pid file, log file and the main script to execute (we create at the beginning of the article).
  3. The main function of the service: this section we declare the service handler. Each function is the corresponding command of the service is start, stop, restart, status.
  4. The case statement: this is the last part of the init file, which it allows creating a menu to call the handler above.

Create logrotate file for service

In the init file, we declare the log file for your program. Of course, as with any other service, the log file will expand every day. And we need to set up the logrotate file for your log file.

Read moreScript send email to admin warning ssh login

You create a file /etc/logrotate.d/getload and copy the content below to the file.

/var/log/getlog.log {
    daily
    size 10M
    missingok
    rotate 4
    maxage 15
    dateext
    compress
    notifempty
    create 644 root root
}

So you have set up logrotate finished for your new service.

Check the result

Now we will check how the new service works. In the image below, you may find that you have made the bash script act as a service.

make-bash-script-run-as-service-in-centos-6-01 Make bash script run as service in CentOS 6
Test service getload is running

In the next image below, we check the text file content in the script we have declared. Notice that each line is added a time stamp and one second apart.

make-bash-script-run-as-service-in-centos-6-02 Make bash script run as service in CentOS 6
Check the results when start getload service

Conclusion

Through this article, you can completely make your scripts run as a service in CentOS 6. Further, you can create realtime programs as you would expect from a script, just like the average load monitor like I did in the article.

If you liked this article, then please subscribe to our YouTube Channel for more video tutorials. You can also find us on Twitter and Facebook.


Share this post to your friends !
If you appreciate what we share in this blog, you can support us by:
  1. Stay connected to: Facebook | Twitter | Google Plus | YouTube
  2. Subscribe email to recieve new posts from us: Sign up now.
  3. Start your own blog with SSD VPS - Free Let's Encrypt SSL ($2.5/month).
  4. Become a Supporter - Make a contribution via PayPal.
  5. Support us by purchasing Ribbon Lite Child theme being using on this website.

We are thankful for your support.

single post bottom banner
«« »»

Got something to say? Join the discussion

Please keep in mind that all comments are subject to our Comment Policy. Your email address will not be published.
This site uses Akismet to reduce spam. Learn how your comment data is processed.