Have you ever started a long-running script in your terminal, only to lose all progress when the session closed? Or maybe you wanted to keep a process running in the background while continuing to use the terminal?
That’s where nohup and & come in handy.
What Are nohup and &?
- nohup: Short for no hang up, it allows a command to keep running even after you log out or close the terminal.
- &: Sends the command to the background, freeing up your terminal for other tasks.
Together, they’re a powerful combo for running persistent background processes.
Basic Usage
Here’s the magic one-liner:
nohup your_command > output.log 2>&1 &
Breakdown:
your_command
: The script or program you want to run.> output.log
: Redirects standard output to a file.2>&1
: Redirects standard error to the same file.&
: Runs the command in the background.
Monitoring the Output
To watch the output in real-time:
tail -f output.log
This is especially useful for debugging or tracking progress.
Cleaning Up: Stopping the Process
To stop the background process:
- Find the process ID (PID):
ps aux | grep your_command
- Kill it:
kill <PID>
- Or, if you want to be sure:
kill -9 <PID>
Pro Tips
- If you forget to redirect output,
nohup
will write tonohup.out
by default. - You can check running background jobs with:
jobs
- To bring a background job to the foreground:
fg %1
Final Thoughts
Using nohup
and &
is a simple yet powerful way to manage long-running or persistent processes in Linux. Whether you’re deploying a server, training a model, or crunching data, this trick can save you time and frustration.