limiting size of logfile from a variable
Solution 1
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.
Solution 2
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
Related videos on Youtube
boudiccas
Updated on September 18, 2022Comments
-
boudiccas over 1 year
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.
-
Admin almost 11 yearsYou 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?
-
Admin almost 11 yearsThe 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 almost 11 yearsAlthough 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.
-
mezi almost 11 yearstry this one: command | head -c 50M > /path/foo.txt
-
mezi almost 11 yearsyou can also use /etc/security/limits.conf to set a limit on filesize under a user.