Ubuntu – Bash script to start and then shutdown/restart various processes

bash

When I start up my development environment, there are a variety of processes I need to run in the background. It is a pain to start them all individually so I want to write a script that starts each one. I can do this just fine but the problem comes when I need to restart them (something I will need to do regularly).

What is the easiest way to capture the process upon starting it and saving that information so that when I run the script again, it will check to see if that information has been saved and then close down those processes before restarting them.

I also want the script to be flexible enough such that if I shutdown the process manually, it will a) not throw an error if it can't find the process and b) not accidentally shut down some other process that has since then shared whatever identifying information I have stored.

Update

More specifically, I want to at least do the following at the moment:

1) Type a short command like "start-dev"

2) Execute the following (Note that I want the second and third commands to run in the background and am using & to do so but not the final command as I want to see the output from passenger as it runs):

  1. Change to my working directory
  2. Start faye as a background process
  3. Start watchr as a background process
  4. Start passenger

So far I have got this

#!/bin/bash
cd ~/path/to/my/working-directory
rackup faye.ru -s thin -E production &
watch refresh.watchr &
passenger start

This works fine but the problem comes when I need to restart all these processes. I first have to track down all their process ids and then kill them before running start-dev again. Therefore I would like to:

4) Type a short command like "restart-dev" which tracks down the processes I have previously run in the background and then kill them before running "start-dev" again. It needs to be able to not throw an error if I have shut down any of these manually and not accidentally shutdown an incorrect process.

Best Answer

I'd tackle it something like this.

#!/bin/bash  

startme() {
    cd ~/path/to/my/working-directory
    rackup faye.ru -s thin -E production &
    watch refresh.watchr &
    passenger start
}

stopme() {
    pkill -f "rackup faye.ru" 
    pkill -f "watch refresh.watchr"
}

case "$1" in 
    start)   startme ;;
    stop)    stopme ;;
    restart) stopme; startme ;;
    *) echo "usage: $0 start|stop|restart" >&2
       exit 1
       ;;
esac
Related Question