The “nohup” command in Linux is used to run another command in the background and ensures that the command keeps running even after you log out or close the terminal. It stands for “no hang up,” which means the command won’t be terminated if the terminal session is ended. Here’s how you can use “nohup” efficiently:
1. Basic Usage:
nohup command-to-run &
Replace “command-to-run” with the actual command you want to run. The “&” symbol puts the command in the background.
Example:
nohup ./script.sh &
2. Redirecting Output:
By default, “nohup” sends output to a file called “nohup.out”. You can redirect the output to a specific file like this:
nohup command-to-run > output.log &
3. Redirecting Standard Error (stderr):
To redirect both standard output and standard error to a file:
nohup command-to-run > output.log 2>&1 &
4. Running Multiple Commands:
You can run multiple commands with “nohup” using a subshell:
nohup sh -c 'command1 && command2' &
5. Running a Command on a Remote Server via SSH:
nohup ssh user@remote-server 'command-to-run' &
6. Viewing the Running Processes:
To view the running “nohup” processes, you can use “ps” or “pgrep” command.
For example:
ps aux | grep 'command-to-run'
7. Killing a “nohup” Process:
Find the process ID (PID) of the “nohup” process using “ps aux | grep ‘command-to-run‘“, then use “kill” to terminate it:
kill PID
8. Running a Command in the Background and Disowning it:
nohup command-to-run &
disown
The “disown” command removes the specified jobs from the job table of the shell, effectively disassociating them from the shell so they will not be terminated when the shell exits.
9. Logging the Start and End Time:
You can log the start and end time of your “nohup” process in your output file for reference:
echo "Started at $(date)" >> output.log
nohup command-to-run >> output.log 2>&1 &
echo "Process ID: $!" >> output.log
These are some efficient ways to use the “nohup” command in Linux, allowing you to run processes in the background without worrying about them getting terminated when you log out.
How do you feel about this post? Drop your comments below..