Last active
November 18, 2021 22:42
-
-
Save grzs/83e9b7406ba3af33ba385b50e2490c53 to your computer and use it in GitHub Desktop.
Monster bash logrotate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
shopt -s extglob | |
PATTERN="my-app.log" | |
MAX=10 | |
# move and recreate | |
DATE=$(date +"%Y-%m-%d") | |
LOGFILE=`ls ${PATTERN}` | |
LOGFILE_NEW="${LOGFILE}.${DATE}" | |
if [ ! -f "${LOGFILE_NEW}" ]; then | |
mv "${LOGFILE}" "${LOGFILE_NEW}" | |
touch "${LOGFILE}" | |
fi | |
# if more files found than maximum, delete the rest | |
PATTERN="${PATTERN}.+([0-9]|-)" | |
FILES=`ls $PATTERN` | |
FILES_ARR=($FILES) | |
test ${#FILES_ARR[@]} -gt ${MAX} && rm ${FILES#*${FILES_ARR[$(( $MAX - 1 ))]}} | |
# # classic logrotate | |
# for i in `seq $(( $MAX - 1 )) 1`; do | |
# if test -f "${PATTERN}.$i"; then | |
# j=$(( i + 1 )) | |
# mv "${PATTERN}.$i" "${PATTERN}.$j" | |
# fi | |
# done | |
# mv "${PATTERN}" "${PATTERN}.1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment