H2 Database Script

Here is a convenient script to control an H2 Database instance from the command line. It is designed for Mac OS X, but may be adapted to Linux using suitable options for the open and ps commands, e.g. `ps -ef`.

#!/bin/sh
#
# Control H2 instance; assumes default port assignments
# Author: John B. Matthews
# License: http://www.h2database.com/html/license.html
#
base=${HOME}
browser=safari
classpath=.:/opt/h2/bin/h2.jar
netstat=/usr/sbin/netstat
ps="ps -axwww"
server=org.h2.tools.Server
webport=8082
defaultports="(5435\|${webport}\|9092\|9094)"

getpid() {
  pid=`${ps} | grep java | grep ${server} | awk '{ print $1 };'`
}

browse() {
  getpid
  if [ `${netstat} -an | grep ${webport} | grep -i listen | wc -l` = "1" ]
    then open -a ${browser} http://localhost:${webport}
  else
    echo "H2 not listening on ${webport}."
  fi
}

start() {
  java -cp ${classpath} ${server} -tcp -web -baseDir ${base} &
  READY=0
  while [ $READY -eq 0 ]
    do
      sleep 1
      READY=`${netstat} -an | grep ${webport} | wc -l`
    done
  open -a ${browser} http://localhost:${webport}
}

stop() {
  getpid
  if [ "${pid}x" = "x" ]
    then echo "No H2 Server running."
  else
    echo "Killing H2 Server process id: ${pid}"
    kill -1 ${pid}
  fi
}

status() {
  getpid
  if [ "${pid}x" = "x" ]
    then echo "No H2 Server running."
  else
    echo "H2 Server has process id: ${pid}"
    ${netstat} -an | grep ${defaultports} | grep -i listen
  fi
}

restart() {
    stop
    start
}

help() {
  java -cp ${classpath} ${server} -?
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  status)
    status
    ;;
  browse)
    browse
    ;;
  help)
    help
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|status|browse|help}"
    exit 1
esac

exit $?