views:

1359

answers:

8

Let's take example of a command "example-command".

  1. I open terminal
  2. I write example-command in terminal, and example-command executes.
  3. Now if I close terminal, example-command gets killed too.
  4. I now try with "example-command &", but the same behaviour.

How do I execute a command so that when I close the terminal, the command doesn't get terminated?

+3  A: 

example-command &; disown {pid}

or just

disown

alamar
NVRAM
alamar
+5  A: 

There are two ways, identical in result.

  1. Use nohup when you start your program. E.g., nohup example-command. You can background and work with it normally; it will simply continue running after you've quit.
  2. Alternatively, as @alamar noted, if you use bash as your shell, you can us the disown command. Unfortunately, as far as I know, disown is bash-specific; if you use another shell, such tcsh, you may be restricted to the nohup form above.
Benjamin Pollack
zsh does also support disown.
alamar
Oh, and now I remember, I've used `nohup` in past!
Vikrant Chaudhary
From the bash man page, it looks like the "-h" option is required to ignore SIGHUP -- "disown -h".
NVRAM
+1  A: 

nohup example-command

hiena
+1  A: 

You can also use the 'at' or 'batch' commands and give it the current time.

Shane C. Mason
I like this one, but rarely use it. And to simplify just use "at now" (no need to figure out the date/time).
NVRAM
+1  A: 

disown is a bash builtin. You could create a wrapper shellscript for your command such as

#!/bin/bash
$1 &
P=`which $1`
disown `pidof ${P}`

Not the most robust script (by any means) but may help get you going. For example:

$./launch_script.sh myProgram

You can also do this in the source of the program if you are editing it.

Aiden Bell
Your example doesn't handle arguments (use "$@"). You can use "$!" for the PID of last backgrounded job. But the PID is not needed. And you should ignore SIGHUP so use either "nohup" or "disown -h".
NVRAM
Thanks NVRAM, been a while since I did any shell scripting :)
Aiden Bell
+3  A: 

You could also consider using the screen command.

MatthieuP
+1  A: 

Hello,

Please search for similar questions first.

Besides the ways listed above, you can do:

setsid command_name

For example:

setsid xclock

Thanks

Bash
>> Please search for similar questions first.*I did. Sir.*
Vikrant Chaudhary
A: 

Run: example-command

Press: Control-Z

Run: bg

Eduardo