nohup Command in Linux with Examples
Every command in Linux starts a process at the time of its execution, which automatically gets terminated upon exiting the terminal. Suppose, you are executing programs over SSH and if the connection drops, the session will be terminated, all the executed processes will stop, and you may face a huge accidental crisis. In such cases, running commands in the background can be very helpful to the user and this is where nohup command comes into the picture. nohup (No Hang Up) is a command in Linux systems that runs the process even after logging out from the shell/terminal.
Usually, every process in Linux systems is sent a SIGHUP (Signal Hang UP) which is responsible for terminating the process after closing/exiting the terminal. Nohup command prevents the process from receiving this signal upon closing or exiting the terminal/shell. Once a job is started or executed using the nohup command, stdin will not be available to the user and nohup.out file is used as the default file for stdout and stderr. If the output of the nohup command is redirected to some other file, nohup.out file is not generated.
nohup command [command-argument ...]
Working with nohup command
1. Checking the version of Nohup:
The version of nohup command can be checked by using the following command.
$ nohup --version
2. To run a command in the foreground:
Runs the command in the foreground and redirects the command output to the nohup.out file if any redirecting filename is not mentioned.
$ nohup bash geekfile.sh
To redirect the output to the output.txt file:
$ nohup bash geekfile.sh > output.txt
3. To run a command in the background (with ‘&’):
To run the command in the background, the ‘&’ symbol is appended at the end of the command. After executing, it doesn’t return to the shell command prompt after running the command in the background. It can be brought back to the foreground with the fg command.
$ nohup bash geekfile.sh & fg
Note: The number within square brackets represents the job id and the number next to it is the process id.
4. To run multiple commands in the background:
nohup command can be used to run multiple commands in the background.
$ nohup bash -c 'commands'
$ nohup bash -c 'cal && ls'
Here, the output will be by default stored in nohup.out. To redirect it, type:
$ nohup bash -c 'commands' > filename.txt
$ nohup bash -c 'cal && ls' > output.txt