I want to have .bashrc check to see if an emacs server is currently running, and if not, start one. I know how to start the server but I am not sure how to check whether it is already running - should I just grep the processes for Emacs? Curious if anyone has something like this set up.
2 Answers
The functionality is built into Emacs. Run emacsclient
and pass it the -a
(long form --alternate-editor
) option with an empty argument, and it'll start Emacs (in daemon mode, i.e. initially without any window) if it isn't already running.
emacsclient -a '' # in sh syntax
emacsclient --alternate-editor= # anywhere whitespace-separated command and arguments work
If you always use this command to open files, Set the EDITOR
and VISUAL
environment variables to it in your ~/.profile
or ~/.bash_profile
or ~/.zprofile
:
export VISUAL='emacsclient --alternate-editor='
export EDITOR='emacsclient --alternate-editor='
and make an alias for it in your ~/.bashrc
or ~/.zshrc
:
alias e='emacsclient --alternate-editor='
Add the option -c
if you want to open a new Emacs window to edit the file. With emacsclient -c
, if you don't pass a file name argument, you get a new Emacs window showing whatever buffer is at the front of the buffer list.
Alternatively, run emacs --daemon
as part of your session startup and use plain emacsclient
to open files.
Note that ~/.bashrc
runs every time you open a terminal, not when you log in. On normal Unix systems, the file that runs when you log in is ~/.profile
(or ~/.bash_profile
, ~/.profile
, etc. depending on your login shell), but OSX does things differently (and actually runs ~/.bash_profile
or ~/.profile
and not ~/.bashrc
when you open a terminal due to a combination of bad design in OSX and bad design in bash: OSX opens a login shell in each terminal and bash doesn't load .bashrc
in login shells — see https://unix.stackexchange.com/questions/110998/missing-source-bashrc-mac-terminal-profile).

- 22,318
- 4
- 56
- 92
I recommend that you create a startup script, with the command emacs --daemon
at startup. Then there is no need to start Emacs server anymore.
See also this link.
Which Linux distro are you running?

- 3,850
- 23
- 66
emacsclient --a ''
- perhaps I am misunderstanding what you mean by empty argument? – Andrew Jun 23 '16 at 22:04EDITOR
variable, because you can't arrange to have an empty word there. That's why I showed the use of--alternate-editor=
, which doesn't require an empty word. – Gilles 'SO- stop being evil' Jun 23 '16 at 22:10e
I getmacsclient: file name or argument required Try emacsclient --help' for more information
- it is still asking me to specify a file. It works fine if I typee filename
. – Andrew Jun 24 '16 at 21:12-c
option. – Gilles 'SO- stop being evil' Jun 24 '16 at 22:15