title: Bash script to start process, wait random, kill process, restart
body: <p>I'm an absolute beginner and am trying to create a bash script to randomize the start and exit of a command line app. I plan to autostart the script on boot (Crunchbang) after a slight delay with the following in autostart.sh (found here: <a href="http://interwebworld.co.uk/2011/10/23/how-to-launch-programs-automatically-at-startup-in-crunchbang-linux/" rel="noreferrer">http://interwebworld.co.uk/2011/10/23/how-to-launch-programs-automatically-at-startup-in-crunchbang-linux/</a> )</p>
  
  <pre><code>(sleep 300s &amp;&amp; /home/myuser/Scripts/randomizer.sh) &amp;
  </code></pre>
  
  <p>This is essentially what I need to accomplish in the randomizer.sh script, in a bit of pseudocode:</p>
  
  <pre><code>start applicationfile
  wait a random period of time
  if applicationfile is still running
      kill its process
      wait a random period of time
      exit this script and restart this script
  else exit this script and restart this script
  </code></pre>
  
  <p>The randomizer.sh as I have it so far and which I'd welcome some help with, is as follows (containing remnants of the pseudocode), and the sleep delay found here: <a href="http://blog.buberel.org/2010/07/howto-random-sleep-duration-in-bash.html" rel="noreferrer">http://blog.buberel.org/2010/07/howto-random-sleep-duration-in-bash.html</a></p>
  
  <pre><code>/path/to/applicationfile -s 111.222.333.444 -u username -p password
  sleep $[ ( $RANDOM % 150 ) + 60 ]m
  if applicationfile is still running
      kill $(ps aux | grep '[u]sername' | awk '{print $2}')
      sleep $[ ( $RANDOM % 150 ) + 60 ]m
      exec $randomizer.sh
  else exec $randomizer.sh
  </code></pre>
  
  <p>I "think" the non-pseudo parts should work pretty much as they are, but please correct me or adjust if I'm wrong. The initial applicationfile command line works as it is, and I already tested the process kill line and it works as expected. Applicationfile doesn't have a built-in way to end itself from commandline, but the dead connection on the remote machine will be killed after 5 minutes of being killed locally, so killing it locally is acceptable for my needs.</p>
  
  <p>What I don't have any idea how to handle is the line above the kill, which checks "if" the process is running in the first place. Sorry for the wall of text but I wanted to show I've done as much as I could already. </p>