Advanced Watch Command Features
In this step, you will learn about some advanced features of the watch
command that can make your monitoring tasks more efficient.
Let's start by exploring the -t
option, which turns off the header showing the command and current time:
watch -n 3 -t date
Notice that the header is now hidden, giving a cleaner display focused only on the command output. This is useful when you want to maximize screen space for the output.
Press Ctrl+C
to exit.
Next, let's look at how to use watch
with the -g
or --chgexit
option. This option makes watch
exit when the output of the command changes:
touch ~/project/test_change.txt
watch -g -n 1 "ls -l ~/project/test_change.txt"
While this command is running, open a new terminal and modify the file:
echo "hello" > ~/project/test_change.txt
The watch
command in the first terminal should exit automatically when it detects the change in the file.
Let's create a more practical example. We'll create a script that simulates a log file with occasional errors:
nano ~/project/simulate_logs.sh
In the nano editor, type the following content:
#!/bin/bash
LOG_FILE=~/project/application.log
## Initialize log file
echo "Starting log simulation" > $LOG_FILE
## Generate simulated log entries
for i in {1..10}; do
echo "[$(date)] - INFO: Normal operation $i" >> $LOG_FILE
sleep 1
## Occasionally generate an error
if ((i % 3 == 0)); then
echo "[$(date)] - ERROR: Something went wrong!" >> $LOG_FILE
fi
done
echo "Log simulation complete" >> $LOG_FILE
Save and exit nano (Ctrl+O
, Enter, Ctrl+X
), then make the script executable:
chmod +x ~/project/simulate_logs.sh
Now, let's use watch
with grep
to monitor for error messages in the log file:
watch -n 1 "grep ERROR ~/project/application.log || echo 'No errors found'"
In another terminal, run the log simulation script:
~/project/simulate_logs.sh
Watch how the first terminal displays when error messages appear in the log file. This is a practical example of using watch
for monitoring logs in real-time.
Press Ctrl+C
to exit the watch command.
Finally, let's see how to run watch in the background and redirect its output to a file:
watch -n 5 date > ~/project/date_output.txt 2>&1 &
This command runs the watch
command in the background, updating the date every 5 seconds and saving the output to a file. You can check the file content:
cat ~/project/date_output.txt
To stop the background watch process, find its PID and kill it:
ps aux | grep "watch -n 5 date"
kill <PID> ## Replace <PID> with the actual process ID number
These examples demonstrate the versatility of the watch
command for various monitoring tasks.