Shell script to grep current PostgreSQL log

All we need is an easy explanation of the problem, so here it is.

I have tried by google but unable to find.

I wanted to grep string from below no. of files which is most recent files.

by using this command i am able to fetch most recent file but , not able to grep in that file only.

ls -lrth 

-rw-r--r--. 1 user pg_user 1712804 Jul 13 22:27 postgresql-2021-07-13_000000.log
-rw-r--r--. 1 user pg_user       0 Jul 14 00:00 postgresql-2021-07-14_000000.log
$ ls -lt postgresql-*.log | head -n 1 
-rw-r--r--. 1 user pg_user       0 Jul 14 00:00 postgresql-2021-07-14_000000.log

now, I want to grep "string" in postgresql-2021-07-14_000000.log

How i can combine both in one command to get output with echo on screen. like below but someting is i am missing.

for example:

$ls -lt postgresql-*.log | head -n 1 | grep "system is ready" 

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You could use xargs:

ls -t postgresql-*.log | head -n 1 | xargs grep "system is ready"

Method 2

You can do it this way. First extract today’s date because what I can see it from your logs is logs are created date wise & latest would be of current date. So, extract current date & then merge it with your file name & extract required content from your log.

 dd=`date +%Y-%m-%d`
grep "system is ready"  postgresql-$dd_000000.log

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply