How to remove temporary files using Linux Scripts

How to remove temporary files using Linux Scripts

To remove temporary files using a Linux script, follow these commands:

#!/bin/bash

# Specify the directory where temporary files are stored
temp_dir="/path/to/temporary/files"

# Remove files older than a certain number of days
find "$temp_dir" -type f -mtime +7 -exec rm {} \;
# This command removes files in "$temp_dir" that are older than 7 days.
# Adjust the value of "+7" to the desired number of days.

# Remove empty directories
find "$temp_dir" -type d -empty -delete
# This command removes empty directories in "$temp_dir".

# Remove specific file types
find "$temp_dir" -type f -name "*.tmp" -exec rm {} \;
# This command removes files with the extension ".tmp" in "$temp_dir".
# Adjust "*.tmp" to match the specific file pattern you want to remove.

# Remove files matching a certain pattern
find "$temp_dir" -type f -name "prefix_*" -exec rm {} \;
# This command removes files starting with "prefix_" in "$temp_dir".
# Adjust "prefix_*" to match the desired file pattern.

# Remove files based on size
find "$temp_dir" -type f -size +1M -exec rm {} \;
# This command removes files larger than 1 megabyte in "$temp_dir".
# Adjust the value of "+1M" to the desired size.

Save the script in a file, like remove_temp_files.sh, and make it executable with the command chmod +x remove_temp_files.sh. Then, run the script by typing ./remove_temp_files.sh in the terminal.

Change the value of $temp_dir to the folder where your temporary files are kept. Modify the find command options to fit your needs for deleting temporary files.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!