Question

I would like a script that does something along the lines of:

if process_name not running
    start process from path /home/data/process_name
    write "date: process start" to /home/data/log.txt

I have never written a bash script, and I dodn't know what to do.

Was it helpful?

Solution 2

Try this:

if ! pgrep process_name; then
  /home/data/process_name &
  echo "$(date): Process start" >> /home/data/log.txt
fi

If do you want to kill process and then start it, try this:

if ! pgrep process_name; then
  /home/data/process_name &
  echo "$(date): Process start" >> /home/data/log.txt
else
  killall process_name
  /home/data/process_name &
  echo "$(date): Process start" >> /home/data/log.txt
fi

OTHER TIPS

On Debian and Ubuntu you can use start-stop-daemon. It has all sorts of options to help identify the right process so that you don't end up starting it twice or killing the wrong one. An example from the man page:

Start  the  food daemon, unless one is already running (a process named
food, running as user food, with pid in food.pid):

    start-stop-daemon --start --oknodo --user food --name food --pidfile /var/run/food.pid --startas /usr/sbin/food --chuid food -- --daemon

This command makes sure that the process belongs to the right user, has the right name, and has a process id matching that in /var/run/food.pid. You don't have to use them all, of course.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top