4

How do you automatically disown an application after you have started it from a terminal?

For example: if you start a terminal and run firefox the application will start, but when you then close the terminal firefox will close as well. To avoid unintentionally closing applications that have been started from a terminal, one can first put them in the background with the ampersant: firefox & which also restores the ability to use that terminal's prompt. Next, you can disown the application from that same terminal using the process ID (PID) of the application, see this example below:

$ firefox & 
$ ps | grep firefox
14917 pts/6    00:00:00 firefox
$ disown 14917

The application now runs independently from the terminal you are using, and closing the terminal will no longer terminate the application.

But how can you do this automatically each time you start an application?

3 Answers3

6

The simplest way is to execute:

daemon firefox

so you can continue using/closing the terminal itself

I-V
  • 235
2

EDIT: a better answer was provided by I-V.

To do this automatically, you could use a bash alias. If you add the following lines to your .bash_aliases file in your home directory, you can start any application my_application from the terminal while automatically putting it on the background and subsequently disowning it from that terminal, using the command s my_application:

# start programs from shell but immediately disown them
startAndDisown() {
    $1 & disown $! 
}
alias s=startAndDisown

Note that $! automatically returns the PID of the last async job.

1

firefox & disown $! doesn't work for me, but a similar solution that works for me is firefox&;disown

Another solution that does not involve disown is to use GNU Screen. It will preserve your terminal session even if you close the terminal window. However it's practicality is bounded by how you use your terminal. If you only use one terminal window at a time, this is a great solution. If you use more terminals, less so. Install screen using your favourite package manager, then everytime you open a terminal type screen -r (or screen if no screen session is running). You then don't have to worry about closing your terminal. This is a very niche solution, but it could fit you.

Dario
  • 11
  • 1