做什么

让进程忽略 SIGHUP——SSH 断 / 关 shell 时进程不死。

实战

nohup long-task &
# nohup: ignoring input and appending output to 'nohup.out'

# 同时指定日志
nohup python app.py > app.log 2>&1 &

# 看后台进程
jobs
ps aux | grep app.py

退出 shell 后用 ps 还能找到这个进程。

输出去哪

  • 不重定向:默认到当前目录的 nohup.out
  • 重定向:> file 2>&1
  • 完全丢弃:> /dev/null 2>&1
# 完全静默后台跑
nohup myscript > /dev/null 2>&1 &

完整套路

nohup /path/to/script.sh > /var/log/script.log 2>&1 &
echo $! > /var/run/script.pid       # 把 PID 存起来便于停

# 停
kill $(cat /var/run/script.pid)

nohup vs tmux / screen vs systemd

工具 适合
nohup 临时长任务(几小时 / 几天)
tmux / screen 想随时回来看 + 多窗口工作
systemd 服务 生产服务,长期跑

nohup 简单但粗糙——一次性临时任务可以;生产服务用 systemd

配 disown 一起用

long-task &
disown                  # 从 jobs 列表移除
# 退 shell 不会发 HUP——等效 nohup

  • nohup 不重定向则默认写 ./nohup.out——如果当前目录不可写会失败
  • 后台运行 (&) ≠ 抗挂断——光 &nohup,关 shell 还是会死
  • nohup 让进程脱离终端,但不切到独立 session——setsid 更彻底