Skip to content

Instantly share code, notes, and snippets.

@MParvin
Created June 30, 2023 11:47
Show Gist options
  • Save MParvin/cadac4740476ab03552aba587a949ca4 to your computer and use it in GitHub Desktop.
Save MParvin/cadac4740476ab03552aba587a949ca4 to your computer and use it in GitHub Desktop.
To manually rotate log files
#!/bin/bash
if [ -z $1 ]
then
echo -e "Usage is: ./main.sh PATH_TO_FILE\nExample: ./main.sh /var/log/nginx/access_log"
exit 1
fi
file=$1
if [ ! -f "$file" ]; then
echo "$file not found"
exit 1
fi
# Variables
rotateDate="$(date +%Y_%m_%d)"
rotatedFile=$file"-ROTATED_IN_$rotateDate"
# Get original file Permissions and Owner
orgOwner="$(ls -l $file | awk '{print $3}')"
orgGroup="$(ls -l $file | awk '{print$4}')"
orgPermission="(stat -c '%a' $file)"
# Rename original file to Rotated file name
mv $file $rotatedFile
# Recreate file
touch $file
# Restore owner and group
chown $orgOwner:$orgGroup $file
chmod $orgPermission $file
gzip $rotatedFile
echo "File rotated successfuly"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment