Linux nohup Command
nohup stands for no hang up, used to run commands in the background without being interrupted when the terminal is exited.
nohup command, by default (without redirection), outputs a file named nohup.out in the current directory. If the nohup.out file in the current directory is not writable, the output is redirected to $HOME/nohup.out.
Usage Permission
All users
Syntax Format
nohup Command [ Arg … ] [ & ]
Parameter Description:
Command: The command to be executed.
Arg: Some parameters, can specify the output file.
&: Executes the command in the background, the command continues to run after the terminal exits.
Example
The following command runs the script tutorialpro.sh in the root directory in the background:
nohup /root/tutorialpro.sh &
If you see the following output in the terminal, it indicates successful execution:
appending output to nohup.out
At this point, you can open the root directory and see the generated nohup.out file.
To stop the execution, you need to find the PID of the nohup running script using the following command, and then use the kill command to terminate it:
ps -aux | grep "tutorialpro.sh"
Parameter Description:
- a: Displays all processes
- u: Displays processes in user-oriented format
- x: Displays all processes, regardless of terminal
Alternatively, you can use the ps -def | grep "tutorialpro.sh"
command to find it.
After finding the PID, you can use kill PID to terminate it.
kill -9 PID
The following command runs the script tutorialpro.sh in the root directory in the background and redirects the input to the tutorialpro.log file:
nohup /root/tutorialpro.sh > tutorialpro.log 2>&1 &
2>&1 Explanation:
Redirects standard error 2 to standard output &1, and then standard output &1 is redirected to the tutorialpro.log file.
- 0 – stdin (standard input)
- 1 – stdout (standard output)
- 2 – stderr (standard error output)