Cron:Examples:LogFileRotate
lastmod 2025-04-17created 2025-04-171 edits
A crontab example that automatically splits log files by date.
Goal
There is a log text file on Linux whose size keeps growing automatically
A script that splits it every day at exactly 00:00:00, automatically naming the file by date as "originalfilename-date.log".
In short, a script that automatically splits a log file every day at 00:00 on Linux
Bash Script
#!/bin/bash
# 설정
LOG_DIR="/path/to/log" # 로그 파일이 있는 디렉토리 경로
LOG_FILE="yourlog.log" # 원본 로그 파일 이름 (ex: yourlog.log)
# 현재 날짜를 가져옴
TODAY=$(date +"%Y-%m-%d")
# 파일 존재 여부 확인
if [[ -f "$LOG_DIR/$LOG_FILE" ]]; then
# 파일 이름을 날짜별로 복사
cp "$LOG_DIR/$LOG_FILE" "$LOG_DIR/${LOG_FILE%.*}-$TODAY.log"
# 원본 파일 초기화
: > "$LOG_DIR/$LOG_FILE"
else
echo "Not found logfile: $LOG_DIR/$LOG_FILE"
fi
Add execute permission to the script:
Editing the crontab
Edit it as follows:
-
0 0 * * *→ runs every day at exactly 00:00 -
/path/to/split_log_daily.sh→ the path where you saved the script above
Notes
- Because it uses the cp command, it is fine for the program to keep writing logs even while the log is being copied.
- The file is reset with
: > 파일명, which empties the file contents without deleting the file itself (the file descriptor is preserved). - You only need to adjust the log file path and name settings (
LOG_DIR,LOG_FILE). - For cron to work properly, the
split_log_daily.shfile needs execute permission:chmod +x /path/to/split_log_daily.sh
Meaning of : > filename in the script
: is a very special "no-op" (no operation) command in bash (the shell). That is, it's "a command that does nothing."
Specifically, : on its own means doing nothing, but when used together with >, it means the following:
: > 파일명
- Makes the file an empty file (reset)
- > means "redirect output to a file", right?
- : means "produces no output"
So it becomes "write nothing to the file" → in the end, the file contents become 0 bytes
That is, the file stays in place and only its contents are wiped clean! Why not delete it with rm and create it again?
Deleting the file with the rm command breaks the file descriptor (FD), so if some program has this log file open (e.g. writing logs in real time), the program may fail to write logs or terminate abnormally.
But if you reset it with : > 파일명, the file is not cut off and only its contents are wiped, so the program can keep writing logs without any problem.