Real-time File Monitoring with tail
One of the most powerful features of the tail command is its ability to monitor files in real-time. This is particularly useful for watching log files as they're being written to.
Let's create a simple script that simulates a log file being continuously updated:
cd ~/project
Create a script file named log_generator.sh:
nano log_generator.sh
Add the following content to the script:
#!/bin/bash
for ((i = 1; i <= 10; i++)); do
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Log entry $i: System event recorded" >> simulation.log
sleep 2
done
Save the file by pressing Ctrl+O, then Enter, and exit nano with Ctrl+X.
Make the script executable:
chmod +x log_generator.sh
Now, let's use the tail command with the -f option to monitor the log file in real-time. The -f option stands for "follow", which makes tail continue to monitor the file for changes.
Open a new terminal window by clicking on the terminal icon in the taskbar (or use the keyboard shortcut Ctrl+Alt+T). In the new terminal, run:
cd ~/project
tail -f simulation.log
Now, go back to your original terminal window and run the log generator script:
./log_generator.sh
In the terminal where you're running tail -f, you should see new log entries appearing every 2 seconds:
[2023-11-01 12:34:56] Log entry 1: System event recorded
[2023-11-01 12:34:58] Log entry 2: System event recorded
[2023-11-01 12:35:00] Log entry 3: System event recorded
...
After the script completes (after about 20 seconds), go back to the terminal where tail -f is running and press Ctrl+C to stop the monitoring.
This real-time monitoring capability makes tail -f an invaluable tool for system administrators who need to watch log files for errors or important events.