Watching a Log File in the Terminal


This post is in the category: Tips

Random small break-fix or enlightening ideas


This bash one-liner will let you watch the tail end of a log file in real time.

I find myself keeping an eye on the Apache log when testing Linux deployments. This helps me see what the clients are requesting, whether the preseed file was fetched, etc. After writing this tip, I had this epiphany that this could be used for any log file. Just swap out /var/log/apache2/access.log with your file of choice.

First, output the end of the Apache2 log file to see the recent requests.

[user]$ tail /var/log/apache2/access.log

Add a few more lines.

[user]$ tail -n 30 /var/log/apache2/access.log

How many lines do I add to fill up the terminal? We can get the terminal height by running tput lines.

[user]$ tail -n $(tput lines) /var/log/apache2/access.log

But that’s not good enough because I want to output a few lines less than the height. More on that later. This calls for an expr, or expression call.

[user]$ tail -n $(expr $(tput lines) - 4) /var/log/apache2/access.log

But what if the line wraps? Then that line is taking up two lines in the terminal. I’d rather truncate (or cut) the lines after the width of the terminal. We can find the width by running tput cols, which creates this command.

[user]$ tail -n $(expr $(tput lines) - 4) /var/log/apache2/access.log | cut -c 1-$(tput cols)

Finally, I’m too lazy to hit up and enter every four seconds, so lets wrap this all in watch.

[user]$ watch -n 4 "tail -n $(expr $(tput lines) - 4) /var/log/apache2/access.log | cut -c 1-$(tput cols)"
This entry was posted in Tips on by .

About Andrew Wells

I have been developing on the LAMP stack since about 2006. I run Ubuntu XFCE on my desktop and have a history of managing Ubuntu and CentOS servers. I code web applications mostly in PHP but have experience with other languages as well. When I'm not working, I can be found working in my home lab or out snowboarding, hiking, camping, or biking depending on the season.

Leave a Reply

Your email address will not be published. Required fields are marked *