Strovent SystemsSign in
Reference

nohup, disown or tmux: keep a command running after SSH disconnects

When SSH drops, the shell sends SIGHUP to its jobs. nohup and disown keep a command alive but you cannot get back to it; tmux keeps it and its screen.

You start a long job over SSH: a backup, a build, a big copy. The connection drops, and when you log back in the job is gone. Here is why, and the three usual ways to stop it.

Why the command ends

When the connection closes, the host's side of the terminal hangs up and the shell gets a SIGHUP (hangup) signal. Bash exits on SIGHUP, and before it goes it sends SIGHUP on to every job it started, running or stopped. Most programs end when they get SIGHUP.

nohup: ignore the hangup from the start

nohup ./backup.sh &

nohup runs the command with hangup signals ignored. Because the terminal will go away, it also moves the command's input and output off the terminal:

  • Input from the terminal is replaced with an unreadable file.
  • Output that would go to the terminal is appended to nohup.out in the current folder, or ~/nohup.out if that is not possible. It tells you so: nohup: ignoring input and appending output to 'nohup.out'.

To choose the file yourself: nohup ./backup.sh > backup.log 2>&1 &.

disown: rescue a job you already started

If the command is already running, you do not have to start again. In Bash:

  1. Press Ctrl+Z to stop it, then type bg to let it carry on in the background. See Ctrl+Z and "Stopped": get the program back with fg, bg and jobs.
  2. Type disown (or disown %1). The job is removed from the shell's job table, so the shell does not send it SIGHUP when it exits.

disown -h keeps the job in the list but still marks it so that it gets no SIGHUP.

The job's output still goes to the terminal that has gone. A program that writes to it after the disconnect can fail at that point, so nohup with a log file, or tmux, is safer for anything that prints.

setsid: start it in a new session

setsid ./backup.sh > backup.log 2>&1 < /dev/null & starts the program in a new session, away from your login's terminal, so the hangup does not reach it.

tmux: keep the terminal too

nohup, disown and setsid keep the process alive, but you cannot get back to its screen, answer a prompt or press Ctrl+C. tmux (or screen) runs the program in a terminal on the host that outlives your connection. After a drop, log in again and reattach:

tmux new-session -A -s main

For anything interactive, or anything you want to watch, use tmux. See Keep your work after a disconnect with tmux, and attach automatically.

When even these are killed at logout

On a Linux host where systemd-logind has KillUserProcesses=yes, logging out ends every process in your login's session scope, including ones started with nohup or inside tmux. See tmux killed on SSH logout: systemd KillUserProcesses and linger.

Sources

Spotted a mistake? Email [email protected].