DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • linux
  • bash alias
  • chmod
  • linux useful command
  • date
  • extract translation from git diff
  • fail2ban
  • globbing
  • localhost
  • mail
  • memo 内存测试
  • nohup(no hang up)
  • setup env
  • ssh

    • ssh 教程
    • github clone
    • ssh.localhost.run 端口转发
    • ssh 安全
  • systemd service
  • 分析ubuntu系统登录日志文件
  • vpn

    • vpn 教程
    • Algo
    • clashX
    • firezone
    • lantern
    • pac 代理配置
    • Setup vpn
    • shadowsocks
    • VPN
    • VPN 速度优化
    • wireguard cron
    • 修改wireguard端口
  • webhook

nohup(no hang up)

nohup ./script.sh > /dev/null 2>&1 &

基本用法

nohup command [args] &
  • nohup:该命令用于忽略挂起(SIGHUP)信号。
  • command:你想要运行的命令。
  • [args]:命令的参数(如果有)。
  • &:将命令放到后台运行。

示例

1. 后台运行脚本

假设有一个脚本 script.sh 需要在后台运行:

nohup ./script.sh &

2. 后台运行并将输出重定向到文件

默认情况下,nohup 会将输出重定向到 nohup.out 文件。如果你希望将输出重定向到指定文件,可以这样做:

nohup ./script.sh > output.log 2>&1 &
  • > output.log:将标准输出重定向到 output.log 文件。
  • 2>&1:将标准错误输出重定向到标准输出。

3. 后台运行并不保存输出

如果你不希望保存任何输出,可以将输出重定向到 /dev/null:

nohup ./script.sh > /dev/null 2>&1 &

4. 后台运行并指定命令

例如,你可以使用 nohup 来启动一个 Python 脚本:

nohup python my_script.py > my_script.log 2>&1 &

5. 检查后台运行的任务

你可以使用 jobs 命令来查看当前会话中所有后台任务:

jobs

6. 杀死后台任务

找到任务的 PID,然后使用 kill 命令:

ps aux | grep script.sh
kill -9 <PID>

注意事项

  • nohup 命令会忽略 SIGHUP 信号,因此即使你关闭终端,会话中的命令也会继续运行。
  • 如果你没有重定向输出,nohup 会将所有输出重定向到 nohup.out 文件。
  • 使用 & 符号将命令放到后台运行,并立即返回到命令提示符。

示例总结

nohup ./my_long_running_script.sh > output.log 2>&1 &

在这个示例中,./my_long_running_script.sh 脚本会在后台运行,所有输出会被重定向到 output.log 文件,且即使关闭终端,脚本也会继续运行。

通过 nohup 命令,你可以确保长时间运行的进程不会因终端会话关闭而被中断。

Last Updated:
Contributors: rosendo
Prev
memo 内存测试
Next
setup env