Very often you may need to delete files in a directory. In fact, this a common requirement while running websites & applications, to remove old files and logs. In this article, we will look at how to create a shell script to delete files in a directory.
Shell Script to Delete Files in Directory
Here are the steps to create shell script to delete files in Directory.
1. Create Empty Shell Script File
Open terminal and run the following command to create an empty shell script file.
$ sudo vi file_deletion.sh
2. Add shell script to delete files in directory
Add the following lines to delete files in a directory.
#!/bin/sh
sudorm -rf
$1
Save and close the file. The above script deletes all files specified in directory passed as shell script command line argument. $1 stands for the folder path string passed in your command line argument.
3. Make the Shell Script Executable
Update the shell script permissions to make it executable.
$ sudo chmod +x file_deletion.sh
Now if you want to delete all files in /home/data then call the above shell script with the following command.
$ sudo ./file_deletion.sh /home/data
If you do not want to pass file location as argument, or if you want to delete the files from same location always, then replace $1 above with the file location e.g. /home/project
#!/bin/sh
sudorm -rf
/home/project
4. Schedule Cronjob (Optional)
This step is optional, if you want to regularly delete the files in a specific location. In this case just open crontab
$ sudo crontab -e
You will see a document with list of cronjobs scheduled in your system. Let us say you want to run the above script once a day at 10.00 AM, then add the following line to this document.
0 10 * * * sudo /home/ubuntu/file_deletion.sh /home/data >/dev/null 2>&1
Save and close the file. In the above command, “0 10 * * *” indicates that the cronjob be run everyday at 10 AM. “sudo /home/ubuntu/file_deletion.sh /home/data” is the command to be executed. As shown, please use sudo to run the script to avoid permission denied errors. Also specify the full path to both shell script as well as the folder whose files you want to be deleted. Finally, we mute the output by redirecting it to /dev/null 2>&1
You may use online crontab generator to generate the above command as per your requirement.
That’s it. Now you have a simple shell script to remove files from any folder on your system.
Also read:
How to Pass Parameters to Shell Script in Linux
How to Create Wildcard Subdomains in Apache
How to Fix NGINX Upstream Connection Closed Prematurely Error
How to Block Referrer Spam in Apache .htaccess
How to Return Value in Shell Script
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.