From what I have read, one way to speed up the emacs startup is to run emacs --daemon on login and then open files using emacslient instead of emacs, which will access the running emacs server instead of creating a new emacs instance.

However, I prefer to not put proframs in my autostart unless absolutely necessary, as a way yo speed up the login process. Is there a robust way to detect if an emacs server is running? This would let me write a simple script that would spawn the emacs server the first time I open a file with emacs.

if emacs_daemon_is_not_running # <-- How do I do this?
    emacs --daemon
emacsclient -c "$@"

4 Answers 4


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=\"\""
  • For fractionally greater readability on that alias, it suffices to replace the \"\" with a space. Alternatively, set the ALTERNATE_EDITOR environment variable (in a shell rc file, or if necessary in desktop environment settings), but set it blank, and then omit the --alternate-editor= part altogether. emacsclient respects the difference between set-but-empty (where it invokes the daemon) and unset (where it fails).
    – Darael
    Mar 14, 2017 at 21:18

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

if ! emacsclient -e 0 >&/dev/null
then emacs --daemon
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.


You can put this in a shell function or script:

if ! ps h -o pid,args -C emacs | grep -q -- --daemon ; then
    emacs --daemon
emacsclient -c "$@"

This assumes you are using the ps from the standard linux procps package. If you are using another ps, the exact options will be different.

  • I went with ps -e -o args | grep -q -- '^emacs --daemon$'. It seemed simpler and more reliable.
    – hugomg
    Oct 21, 2015 at 2:25
  • yeah, the pid isn't needed - i only put it in there out of habit. ps -C emacs, however, is more reliable than ps -e | grep '^emacs'
    – cas
    Oct 21, 2015 at 2:29

You can do this with ps and or:

ps -e -o args | grep -qE 'emacs --(bg-|)daemon' || emacs --daemon

Inspired by cas and hugomg answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .