nohup(no hang-up)是一个在Linux和Unix系统上用于在后台运行命令的实用程序,即使关闭终端或断开连接,它也会继续运行。以下是一些在Ubuntu上使用nohup的技巧:
基本用法:
nohup command &
这将在后台运行command,并将输出重定向到名为nohup.out的文件。
将输出重定向到指定文件:
nohup command > output.log 2>&1 &
这将把标准输出和标准错误都重定向到output.log文件。
在指定目录下运行命令:
nohup command > /path/to/output.log 2>&1 &
这将在指定的目录下创建output.log文件,并将输出重定向到该文件。
使用nohup运行Python脚本:
nohup python script.py > output.log 2>&1 &
这将在后台运行Python脚本,并将输出重定向到output.log文件。
查看后台运行的进程:
jobs
这将显示当前终端会话中运行的后台进程。
结束后台进程:
kill [process_id]
使用kill命令和进程ID(process_id)来结束后台进程。例如,要结束进程ID为12345的进程,请运行:
kill 12345
使用nohup运行多个命令:
nohup bash -c 'command1; command2' > output.log 2>&1 &
这将在后台运行command1和command2,并将输出重定向到output.log文件。
使用nohup运行带有环境变量的命令:
nohup env "VAR_NAME=value" command > output.log 2>&1 &
这将在后台运行command,并设置名为VAR_NAME的环境变量,值为value。输出将被重定向到output.log文件。
使用nohup运行带有输入重定向的命令:
nohup command < input_file > output.log 2>&1 &
这将在后台运行command,并将input_file作为输入。输出将被重定向到output.log文件。
使用nohup运行带有时间限制的命令:
timeout 10 nohup command > output.log 2>&1 &
这将在后台运行command,并在10秒后自动终止。输出将被重定向到output.log文件。