Linux commands
Browse topics

Keeping a command running after logout with nohup

Version
unversioned
Review
Draft

Summary#

nohup starts a command with the hangup signal ignored, so closing the terminal does not stop it. It does not put the command in the background by itself.

Syntax#

sh
nohup ./job.sh > job.log 2>&1 &
nohup ./job.sh &
disown -h %1

& returns the prompt at once. Redirect both output streams so you know where they go. When standard output is a terminal, nohup appends it to nohup.out. In Bash, disown -h protects a job that is already running.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  job=
  trap 'if [ -n "$job" ]; then
      kill "$job" 2>/dev/null || true
      wait "$job" 2>/dev/null || true
    fi
    rm -rf -- "$dir"' EXIT

  nohup sleep 30 > "$dir/job.log" 2>&1 &
  job=$!
  until [ "$(ps -o comm= -p "$job")" = sleep ]; do sleep 0.1; done

  kill -HUP "$job"
  sleep 0.5
  kill -0 "$job"
  echo 'still running after SIGHUP'
  kill -TERM "$job"
  wait "$job" || echo "stopped by TERM, status $?"
  job=
)

Expected output#

Text
still running after SIGHUP
stopped by TERM, status 143

Common mistakes#

nohup only ignores SIGHUP. TERM, KILL, a reboot or a service manager that ends the login session can still stop the process. A command that reads from the terminal cannot continue after you leave, so give it input from a file or /dev/null. For a program that must restart after failure or at boot, define a systemd service instead.

Version applicability#

This entry describes nohup from GNU Coreutils. Its messages differ between implementations, and some distributions ship a Rust reimplementation of Coreutils.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0