In the world of shell scripting, it’s common to run commands that take a while to complete or need to continue running even after you log out. The nohup
command comes to the rescue. In this article, we’ll delve into how to use the nohup
command with options to run commands in the background and ensure they persist beyond your session. The nohup
command, combined with its various options, is a powerful tool for running commands in the background, particularly for long-running processes and automated scripts.
Understanding the nohup
Command
nohup
stands for “no hang up.” It is used to run a command immune to the hang-up (HUP) signal, which is sent to a process when the user logs out. This allows a command to keep running even after you exit your shell session.
Basic Usage of nohup
The basic syntax for using nohup
is as follows:
nohup command [options] [arguments] &
command
: The command you want to run.options
: Optional flags or settings fornohup
.arguments
: Any arguments to be passed to the command.&
: This symbol is used to run the command in the background.
Using nohup
with Options
nohup
provides several options to control its behavior. Let’s explore some common options with examples:
-c
or--no-clobber
: Prevents overwriting an existing output file.
nohup -c ls > output.txt &
-e
or--no-stderr
: Redirects stderr to the same file as stdout.
nohup -e errors.log command > output.txt &
-p
or--preserve
: Preserves the exit code of the command.
nohup -p command
echo "Exit code: $?"
-g
or--chdir
: Changes the working directory before executing the command.
nohup -g /path/to/directory command
Example Usage
Let’s explore some examples to see how nohup
with options works:
nohup -c echo "Hello, world!" > output.txt &
In this example, the -c
option prevents overwriting output.txt
if it already exists, and the command runs in the background.
nohup -e errors.log ls /nonexistent-directory > output.txt &
Here, the -e
option redirects stderr to errors.log
, so any errors from the ls
command will be captured in the log file.
nohup -p sleep 10
echo "Exit code: $?"
In this example, the -p
option preserves the exit code of the sleep
command, allowing you to check it afterward.
nohup -g /path/to/directory touch file.txt
The -g
option changes the working directory to /path/to/directory
before executing the touch
command.