9

I like to start GUI programs from the terminal, e.g. emacs myfile.txt. But doing that leaves a terminal window open with that process, so now there are two windows for me to keep track of. And if I close the terminal window, the GUI program closes.

I know I can run exec cmd, where cmd is the command I'm trying to run, and that closes the terminal window after the program completes. But I want to close the terminal window after the command is launched. Is there a way to do that?

Jonathan
  • 1,270

1 Answers1

10

You can append this function to your ~/.bashrc:

openclose() {
    "$@" &
    disown
    exit
}

Test it by opening a new terminal (or source ~/.bashrc) and issue

openclose emacs myfile.txt
  • "$@" & runs the command in the background.
  • disown removes the background process from the shell (see help disown and man bash, section SIGNALS), so when the shell is closed the process survives.
  • exit exits the shell.
Quasímodo
  • 18,865
  • 4
  • 36
  • 73
  • Another option is to append && exit to any command you expect to end succesfully. In your case, emacs myfile.txt && exit. – Stewart May 16 '20 at 19:15
  • @Stewart That won't get rid of the terminal window right after Emacs is launched, but only after Emacs is finished. – Quasímodo May 16 '20 at 19:17
  • Wouldn’t the disown be needed only if the shell (Bash) were a login interactive shell and with huponexit enabled? I would expect everything to work just fine by running the command in the background alone, and then exit from the shell immediately. The kernel should not send SIGHUP to the command because it is in the background. – LL3 May 17 '20 at 00:33
  • @Quasímodo Certainly, what I meant is that by making the shell exit on its own accord via exit, its windows should close gracefully without sending SIGHUP to Bash. As such, Bash would not re-send any signal as it didn’t receive any signal. And the kernel won't SIGHUP the Emacs as it's been run in the background. – LL3 May 17 '20 at 13:27
  • @LL3 Oh yes, with exit that's true (would not be true with kill -s SIGHUP, but of course not the case here), sorry for misreading your question and thank you for pointing that out. Even though it is very unlikely that someone will have both the login shell and huponexit enabled, I'm leaving disown there because it is more general. – Quasímodo May 17 '20 at 14:11