note: This question might have been asked before ( I think I saw it somewhere), but a quick search did not reveal anything.

I would like to tell the difference when a command is run from a shell.

Emacs can be initialized with the -nw flag to disable the gui window, and I want this to be the default behaviour. However if emacs is run from a non-shell environment, ( e.g. from the Open With in your filemanager, a desktop configured hotkey, or even from bashrun ), it should not be called with the -nw flag.

update: This should be a global change, running sudo emacs in Terminal should'nt suddenly open a gui. Where do I make these changes?

2 Answers 2


Say this:

$ echo "alias emacs='emacs -nw'" >> ~/.bashrc

Log out, then log back in, and you will get the behavior you are asking for. The alias applies only to Bash.

  • and how do I get passed bashrun?
    – Stefan
    Nov 3, 2010 at 18:04
  • According to the manual, bashrun doesn't read ~/.bashrc. If the manual is wrong, you can say "unalias emacs" in $XDG_CONFIG_HOME/bashrun/rc to remove the alias for bashrun. Nov 3, 2010 at 18:09
  • mmm... you win! but.. Gilles wins more :) ( I want to cover more than just bash )
    – Stefan
    Nov 3, 2010 at 19:01
  • @Stefan I think most shells load from .bashrc; if they don't they almost certainly have an equivalent configuration file you could put the same line in Nov 3, 2010 at 23:29
  • 1
    Putting my solution into .profile will work if /bin/sh is Bash or another shell that understands aliases, but that is not the case on all systems. That said, I don't see why it really matters. /bin/sh exists for running shell scripts, not for interactive use, which use of X implies. If you have a shell script you wrote for use interactively, instead of trying to shoehorn my solution into working for /bin/sh, just put #!/bin/bash or whatever at the top instead. Nov 4, 2010 at 16:36

I think you want to determine if a command is run in a terminal.

if [ -t 2 ]; then
  # Standard error is a terminal
  emacs -nw "$@"
elif [ -n "$DISPLAY" ]; then
  # An X display is available
  xterm -e emacs -nw "$@"
  # We have nothing
  emacs --daemon "$@"

If you want this to always happen when you run Emacs, put it in a script and invoke that script instead. You can call the script /usr/local/bin/emacs (assuming Linux) if you want it to be called emacs and invoked in preference to the “real” emacs executable in /usr/bin.

Note that to edit files as root, you should use sudoedit (benefits: the editor runs as you so you get all your settings; the edited file is put into place atomically when you finish editing, reducing the chance of a mishap). You can also edit files as root directly inside Emacs by opening /sudo::/path/to/file.


You must log in to answer this question.

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