How can I run the emacs daemon only when needed?

You shouldn't even need to test if emacs is already running or not. emacsclient can start the emacs daemon if it's not already running. From emacsclient(1):

   -a, --alternate-editor=EDITOR
          if the Emacs server is not running,  run  the  specified  editor
          instead.   This can also be specified via the `ALTERNATE_EDITOR'
          environment variable.  If the  value  of  EDITOR  is  the  empty
          string,  run `emacs --daemon' to start Emacs in daemon mode, and
          try to connect to it.

I use an alias, ge, for editing files, defined like this:

alias ge="emacsclient -c -n --alternate-editor=\"\""

You can use emacsclient itself to test if there is a connection:

#!/bin/sh
if ! emacsclient -e 0 >&/dev/null
then emacs --daemon
fi
emacsclient -c "$@"

-e 0 means evaluate the expression "0", which just prints 0. The return code is non-zero if emacsclient fails to connect to the server.

Tags:

Emacs