How to open a file from bash command line in the already open Emacs instead of a new instance? When I type

$ emacs file.txt

it opens a new Emacs instance, instead of opening the file in the existing Emacs instance. Mac OS X 10.6.8. and

GNU Emacs 23.4.1 (x86_64-apple-darwin10.8.0, NS apple-appkit-1038.36)

of 2012-02-27 on beta.macosforge.org


what you are looking for is emacs server mode. Add this line to your .emacs file:


Then, open the file using emacsclient:

emacsclient foobar.txt

Have a look at this page for more information.

To avoid having to start emacs manually or setting it to auto-start, you could write a little function that tries connecting to a running server (by running emacsclient) and if not, runs emacs instead. Add this to your shell's configuration file (e.g. ~/.bashrc):

    emacsclient "$@" 2>/dev/null || /usr/bin/emacs "$@" 

Now, simply running emacs file will either start the server or connect to an existing instance.

  • But then it means that one has to keep track and remember whether he/she already started a server or not... Is there a better way? – Dror Jul 11 '14 at 7:11
  • @Dror not at all, when you add this to your emacs configuration file, it will simply launch the server the first time you run emacs and then open all subsequent files in that instance. You don't need to keep track of anything at all. – terdon Jul 11 '14 at 9:26
  • 1
    But if emacs was not started, then emacsclient will yield an error. – Dror Jul 11 '14 at 9:58
  • @Dror ah, yes, I see what you mean. See updated answer. – terdon Jul 11 '14 at 10:08
  • Doesn't work for me. If emacs server hasn't been started, the command does nothing. – godblessfq Jul 13 '15 at 21:06

I'm afraid I cannot recall where I found the following solution. Sorry. However, since it worked optimally for me I add it here.

Make sure that your .emacs starts the emacs server.


Next, in your .bashrc define the function:

function run_emacs
/usr/bin/emacsclient "$1" &

and set the environment variables:

export EDITOR=emacsclient

Finally, define the alias:

alias emacs='run_emacs'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.