Linux Shell Script to Start/Restart Services based on File Existence

This script looks for a file existence and it exists, it will restart apache. You can replace the following parameters to work based on your needs.

file_path --> /path/to/file that you want to watch for existence.

sudo service apache2 restart --> replace this command with the relevant restart command that you want to run.

 #!/usr/bin/env bash

file_path="/home/vagrant"

watch_file=`ls /home/vagrant | grep test_file`

watch() {
  if [ ! -z $watch_file ]
  then
    echo "restarting apache....."
    sudo service apache2 restart
    if [ $? == 0 ]
    then
      echo "apache successfully restarted"
    else
      echo "apache restart failed"
      exit 1
    fi
  else
    echo "There is no test_file"
  fi
}
watch

You can make it as a monitoring script by adding it to your system crontab entry.

For exmaple, to run it every minute, you can use the following syntax.

*/1 * * * *  bash /path/to/watch.sh