views:

58

answers:

3

I am a novice at Bash scripting but I'm a quick learner. Usually. I'm trying to write a script to kill and restart an instance of Hudson--it needs to be restarted to pick up changes in environment variables. What I have so far:

#!/bin/bash
h=`pgrep -f hudson`
if test "$h" != ""; then
  kill $h
  while [ "$h" != "" ]; do
    sleep 1
    unset h
    h=`pgrep -f hudson`
  done
fi
java -jar ~/hudson/hudson.war &

The script correctly determines the running Hudson instance's PID and kills it. However, it just waits after the "kill" line and doesn't proceed. If I hit a key there it completes killing the process and exits the script, never even getting to the while loop. Clearly I'm missing something about how the process should be killed. It's not that the Hudson process is hung and not responding to "kill"; it exits normally, just not until I intervene.

I'm also sure this could be much more efficient but right now I would just like to understand where I'm going wrong.

Thanks in advance.

A: 

If you are using Hudson via an RPM, it comes with an init script already. If not, I'd take a look at them and see if you can base your script off of them: https://hudson.dev.java.net/svn/hudson/trunk/hudson/main/rpm/SOURCES/ (guest//guest).

mrooney
+1  A: 

This represents some straightforward improvements to your script:

#!/bin/bash
h=$(pgrep -f hudson)    # $() is preferred over backticks
if [[ -n $h ]]; then    # this checks whether a variable is non-empty
  kill $h
  while [[ -n $h ]]; do
    sleep 1
    h=$(pgrep -f hudson)    # it's usually unnecessary to unset a variable before you set it
  done
fi
java -jar ~/hudson/hudson.war &

However, it's likely that this is all you need (or use the provided facility that mrooney referred to):

while pkill hudson; do sleep 1; done
java -jar ~/hudson/hudson.war &
Dennis Williamson
Thanks for the bash tips and the obviously better refactor.
AndrewRich
+2  A: 

How about being nice to Hudson and let it shut down itself. I found the following statement in the Hudson forum:

I added http://server/hudson/exit to 1.161. Accessing this URL will shutdown the VM that runs Hudson.

You can call the URL with wget. You can still kill Hudson if it doesn't shut down in an appropriate time.

EDIT: I just stumbled over another thread, with interesting restart options. It uses commands of the build in Winstone server. Not sure if it will pick up changes to environment variables.

Peter Schuetze
Thanks for the extra info. That will be useful.
AndrewRich