Linux Service Restart Script

I required a way to easily restart some common services on my Raspberry Pi running Plex since I kept forgetting whether I needed to use the:

service NAME restart

syntax, or the:

systemctl restart NAME

syntax for the services.

So I created a bash (.SH) file that would allow me to chose which service to restart without having to remember the different commands. Below are my requirements:

  • Give a list of services
  • read which service to restart
  • Restart service
  • restart script

You can see my script below:

#!/bin/bash

restart_script () {
 bash /home/pi/restartservices
}


NUMBER=1
echo "$(tput setaf 3)Following services available:"
echo ""

#LIST SERVICES

for SERVICE in "VSFTPD" "Plex" "VNC Server" "LightDM"
 do
 echo "$(tput setaf 3)($NUMBER)$(tput setaf 7)$SERVICE"
 NUMBER=$[$NUMBER +1]
done

echo ""
echo "$(tput setaf 3)(E)xit:"

read -p "$(tput setaf 3)Chose a service to restart:" READINPUT

if [ $READINPUT = "1" ]
 then
 echo "$(tput setaf 3)Restarting VSFTPD Service...."
 sudo service vsftpd restart
 echo "$(tput setaf 2)Success!"
 restart_script
elif [ $READINPUT = "2" ]
 then
 echo "$(tput setaf 3)Restarting Plex Service...."
 sudo service plexmediaserver restart
 echo "$(tput setaf 2)Success!"
 restart_script
elif [ $READINPUT = "3" ]
 then
 echo "$(tput setaf 3)Restarting VNC Server...."
 sudo service vncserver restart
 echo "$(tput setaf 2)Success!"
 restart_script
elif [ $READINPUT = "4" ]
 then
 echo "$(tput setaf 3)Restarting LightDM Service...."
 sudo systemctl restart lightdm
 echo "$(tput setaf 2)Success!"
 restart_script
elif [ $READINPUT = "E" ] || [ $READINPUT = "e" ]
 then
 echo "$(tput setaf 3)Exiting Script"
 exit 1
else
 echo "$(tput setaf 1)INVALID RESPONSE - WILL LOOP UNTIL RESPONSE IS VALID!"
 restart_script
fi

Rather than having to type in the name of the service I wanted to restart, I used a for loop to add a number to each entry in the services list. This can be found from line 14 to line 19.

Then to run my script from a terminal session, I simply type “./restartservices”

Enjoy!


One thought on “Linux Service Restart Script

  1. […] my previous post, found here, you can see that I have formatted the text to be a specific colour dep... https://itdelinquent.wordpress.com/2018/03/21/coloured-bash-output-using-tput

Leave a Reply