The nohup commands accept a command or an executable as an argument. Once you run a command with nohup, it ignores hangup signals (SIGHUP), which helps keep a process running after closing the shell session.
For example, if you run a command over SSH, all the processes initiated in the SSH session will close once the SSH session dies. You can keep this from happening using a terminal multiplexer such as tmux or screen or use nohup.
How to Use the nohup command
To use nohup, we pass the command as an argument. The general syntax for the command is:
How to run a command with nohup
To run a command, such as a ping, with nohup, use the command:
Once you run the command with nohup, you should get an output such as:
By default, nohup runs a process in the foreground while redirecting the output to nohup.out file. The file is located in the current working directory unless the user does not have write permissions in that directory. In that case, the nohup.out file is created in the user’s home directory.
To view the contents of the nohup.out file, use the cat command as:
How to Use Nohup with background processes
Running a background process is the most effective way to use the nohup command. Running a background process with nohup allows you to close the parent process (shell) without killing your process.
To do this, use the ampersand after the command as:
Once you execute the above command, the shell will launch the sleep command in the background and attaches the ignore SIGHUP to the process.
To view background processes, use the jobs -l command.
How to redirect nohup output to a file
If you do not specify the output file, nohup redirects the output to a nohup.out file. You can override this by using the redirection symbols.
For example, to redirect the output of the ping command to ping.out, use the command:
Adding the file descriptors 1 and 2 enables standard output, and standard error redirects to the ping.out file.
You can also choose different files for both standard output and standard error. Like:
Conclusion
We can use the nohup command to prevent a process from terminating once the parent process terminates. Using redirection parameters, we can also redirect the output from nohup to a custom file.