0
0
Bash Scriptingscripting~30 mins

Log rotation script in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Log rotation script
📖 Scenario: You manage a server that creates a log file called app.log. Over time, this file grows large and needs to be rotated to keep the system tidy and save space.Rotating logs means renaming the current log file to keep it as a backup and starting a fresh empty log file for new entries.
🎯 Goal: Create a simple bash script that rotates the app.log file by renaming it with a numbered suffix and then creating a new empty app.log file.
📋 What You'll Learn
Create a variable for the log file name app.log.
Create a variable for the maximum number of backups to keep, set to 3.
Write a loop to rename existing backup files by increasing their number suffix by 1, starting from the highest number.
Rename the current app.log to app.log.1.
Create a new empty app.log file.
Print a message confirming the rotation.
💡 Why This Matters
🌍 Real World
Log rotation is a common task in system administration to keep log files manageable and prevent disk space issues.
💼 Career
Knowing how to automate log rotation with scripts is useful for junior sysadmins, DevOps engineers, and anyone managing servers.
Progress0 / 4 steps
1
Set up the log file variable
Create a variable called logfile and set it to the string app.log.
Bash Scripting
Need a hint?

Use logfile="app.log" to create the variable.

2
Set the maximum number of backups
Add a variable called max_backups and set it to 3.
Bash Scripting
Need a hint?

Use max_backups=3 to set the number.

3
Rename existing backups with a loop
Write a for loop that counts down from max_backups to 1. Inside the loop, rename each existing backup file app.log.N to app.log.N+1 if it exists. Use mv command and check if the file exists with [ -f filename ].
Bash Scripting
Need a hint?

Use a C-style for loop: for (( i=max_backups; i>=1; i-- )) and inside check if the file exists before moving it.

4
Rotate current log and create new empty log
Rename the current app.log to app.log.1 using mv. Then create a new empty app.log file using touch. Finally, print the message "Log rotated successfully." using echo.
Bash Scripting
Need a hint?

Use mv "$logfile" "$logfile.1" to rename the current log, touch "$logfile" to create a new empty file, and echo to print the message.