/ Linux

Creating a BASH init startup script


Create a simple bash init script, and pass the arguments to stop or start a process. In this example we will use the init script to control tcpdump.

Pre-Requisites:

Create, and apply permissions.

$ touch /etc/init.d/tcpmonitor
$ chmod +x /etc/init.d/tcpmonitor

Open /etc/init.d/tcpmonitor

#!/bin/bash

start() {
   echo "starting tcpmonitor"
   screen -S tcpmonitor -m -d sh -c 'tcpdump -n -w /tmp/file.pcap'
   sleep 2
   echo "tcpdump started with PID of $(ps fax | grep tcpdump | grep -v grep | head -1 | awk '{print $1}') and logging to /tmp/file.pcap"
   echo "started tcpdump ["$(tput setaf 2)OK$(tput sgr0)"]"
}

stop() {
   echo "stopping tcpmonitor"
   screen -X -S tcpmonitor quit
   sleep 2
   echo "tcpmonitor stopped ["$(tput setaf 2)OK$(tput sgr0)"]"
}

case "$1" in
   start) start ;;
   stop)  stop;;
   *) echo "usage $0 start|stop" >&2
      exit 1
      ;;
esac

Script Usage:

This will load tcpdump in the memory, and log info to a file

$ /etc/init.d/tcpmonitor start

This will terminate tcpdump from the memory

$ /etc/init.d/tcpmonitor stop