How can I limit the size of a log file, which is saved in the form of 'foo.txt', from within a bash script please? I want to put in the variables 'LOGFILE=50 mb' and it uses that size, or whatever size LOGFILE is.

This is on Debian 7, fully up-to-date.

  • 2
    You need to explain further. Does the same batch file generate the log? What do you want to happen to log data after the limit is reached? What problem are you trying to solve?
    – Johan
    Jul 1, 2013 at 10:40
  • The variable will be defined in backup-v5.5.conf and will take the form of log-max = 50 mb, and it generates the log file of backup.txt. Once log-max reached, it should roll over and create a new log file.
    – boudiccas
    Jul 1, 2013 at 11:12

3 Answers 3


You need to use logrotate. Do something like this

cat /etc/logrotate.conf

/path/foo.txt {

    size 50M

    create 700 root root

    rotate 5


size 50M – logrotate runs only if the filesize is equal to (or greater than) this size.

create – rotate the original file and create the new file with specified permission, user and group.

rotate – limits the number of log file rotation. So, this would keep only the recent 5 rotated log files.

  • Although this would work, I really need it as a variable within the script so that it can easily be set by others without any problems, and is easily transferable to use in other scripts too. I have done this logrotate tip for myself, but still need it for other scripts as a variable.
    – boudiccas
    Jul 1, 2013 at 11:23
  • try this one: command | head -c 50M > /path/foo.txt
    – mezi
    Jul 1, 2013 at 12:52
  • you can also use /etc/security/limits.conf to set a limit on filesize under a user.
    – mezi
    Jul 1, 2013 at 12:58

I used tail to do that. It's more of a quick and dirty solution respect to logrotate, but it does the job.

Here's what I put in my script:

# in the preceding lines, the log file is updated, with new content at the 
# bottom.
# every update causes the file to exceed the size limit (set to 1MB)

# using tail, put the last 1MB of the file in a temporary file
/usr/bin/tail -c 1MB /your/path/here/logfile.log > /your/path/here//temp 2>&1

# overwrite the older and oversized log file with the new one
/bin/mv /your/path/here/temp /your/path/here/logfile.log

Something like that?

typeset -i LFSB LFSM LOGFILE=50
let LFSB=$(stat -c "%s" $LF)
# This is bytes - turn into MB, base 2
let LFSM=${LFSB}/1048576
if [ $LFSM -gt $LOGFILE ]
    echo Logfile $LF is greater than $LOGFILE MB
    echo Logfile $LF is less or equal than $LOGFILE MB

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .