Question

I have msgbak-.tar.gz files in /var/log/ directory
how can i list all of them using ls -lrt command
i used following script but it doesn't work

LGNAME="/var/log/msgbak"
touch $LGNAME-$(date)
$(ls -lrt $LGNAME*)
OR
$(ls -lrt {$LGNAME*})

any help pointer/indicators please ?

I was trying following,
LGNAME="/var/log/msgbak" MAX_LOG_BACKUP=10

for taredfile in $(ls -lrt $LGNAME*)
do
if [ $(ls -lrt $LGNAME* | wc -l) -lt "$MAX_LOG_BACKUP" ]; then
echo
break;
fi
rm $taredfile
done

This is what i was trying , i know its not bestway but i dont know what went wrong there.

Was it helpful?

Solution

The following works correctly for me to get the number of such files.

ls $LGNAME* | wc -l

If you wanted them sorted in reverse timestamp order, this should work fine:

ls -rt $LGNAME*

To answer the more general question, you could do something like this. I am not sure exactly what modifications you would need to make to make it work in a non-bash shell though.

LGNAME="/var/log/msgbak"
count=$(ls $LGNAME* | wc -l)

if [ "$count" -gt 10 ]; then
    ls $LGNAME* | head -n 1 | xargs rm
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top