Bash Script to Monitor Log File in Real-Time
tail -f /path/to/logfile in a Bash script to monitor a log file in real-time, showing new lines as they are added.Examples
How to Think About It
tail -f command does this by following the file and printing new lines as they come. Your script just needs to run this command with the log file path.Algorithm
Code
#!/bin/bash LOGFILE="$1" if [[ ! -f "$LOGFILE" ]]; then echo "File not found: $LOGFILE" exit 1 fi echo "Monitoring $LOGFILE. Press Ctrl+C to stop." tail -f "$LOGFILE"
Dry Run
Let's trace monitoring /tmp/app.log through the code
Check if file exists
File /tmp/app.log exists, so continue
Print monitoring message
Prints: Monitoring /tmp/app.log. Press Ctrl+C to stop.
Run tail -f
Starts showing new lines added to /tmp/app.log
| Step | Action | Value |
|---|---|---|
| 1 | Check file | /tmp/app.log exists |
| 2 | Print message | Monitoring /tmp/app.log. Press Ctrl+C to stop. |
| 3 | Run tail | tail -f /tmp/app.log |
Why This Works
Step 1: Check file existence
The script first checks if the log file exists using [[ -f "$LOGFILE" ]] to avoid errors.
Step 2: Inform user
It prints a message so the user knows monitoring started and how to stop it.
Step 3: Follow file changes
The tail -f command keeps the script running and outputs new lines added to the log file in real-time.
Alternative Approaches
#!/bin/bash LOGFILE="$1" if [[ ! -f "$LOGFILE" ]]; then echo "File not found: $LOGFILE" exit 1 fi inotifywait -m -e modify "$LOGFILE" | while read -r; do tail -n 10 "$LOGFILE" done
#!/bin/bash LOGFILE="$1" LAST_SIZE=0 while true; do CURRENT_SIZE=$(stat -c%s "$LOGFILE") if (( CURRENT_SIZE > LAST_SIZE )); then tail -c +$((LAST_SIZE + 1)) "$LOGFILE" LAST_SIZE=$CURRENT_SIZE fi sleep 1 done
Complexity: O(n) time, O(1) space
Time Complexity
The script runs continuously, processing new lines as they arrive, so time depends on log growth (n lines).
Space Complexity
Uses constant extra memory since it streams output without storing the whole file.
Which Approach is Fastest?
tail -f is efficient for real-time monitoring; alternatives like polling or inotify add complexity or dependencies.
| Approach | Time | Space | Best For |
|---|---|---|---|
| tail -f | O(n) | O(1) | Simple, real-time monitoring |
| inotifywait | O(n) | O(1) | Event-driven monitoring, efficient but needs extra tool |
| Polling with sleep | O(n) | O(1) | Works without extra tools but less efficient |
tail -f for simple real-time log monitoring in Bash scripts.tail -f causes errors.