How to Write a Shell Script to Delete Files


Removing files using the command line is a simple task with the right arguments. However, if you have a lot of files to delete or you want to automate it, creating your own shell script to delete files is easy and takes very little time. All you need is a basic knowledge of the command line in a Unix environment and your favorite text editor in order to write a simple shell script to delete files.

Things You'll Need

  • Text editor
  • Open your command line interface and start a text editor. The most common one is Vi, but if you have a favorite, such as Emacs or Nano, feel free to use that instead. Name your script something descriptive, such as "delete_script."

  • Type your first line: "#!/bin/bash", as you will be using bash to interpret the script. For your second line, write a comment that tells you what the script does. For this script, use the comment "#Removes files." The "#" at the beginning of the line tells the interpreter that this is a comment.

  • Write the line to delete your files. Since you are using this script to delete any files or folders, it's best to use the command "rm -ri". The "-r" argument will delete all files if you pass a folder to the script and the "-i" will ask you to confirm that you want to delete your files. Instead of putting a specific filename in your script, use "$", which will substitute the file you pass to it when you run the script. The whole script line should be "rm -ri $".

  • Add one more line that confirms the deletion of files: "echo "Deleting files $" ". The "$" argument echos anything passed to the script from the command line. Save your file and exit the text editor.

  • Create permissions on your script so you can run it. Type "chmod 755 your_script". Make sure that the folder your script is located in is in your path. If it's not, you can browse to the folder it's in to run it.

  • Run the script to test it. Create a test file, preferably in the same folder as the script, then run the following command: "./delete_script testfile". If you used the "-i" argument, the command line will ask you to confirm the deletion of the file. If you also added the last line "Deleting files," you should see this after the confirmation before your command line returns to the shell prompt. You can use "ls" to check that your file has been deleted.

Related Searches


  • Photo Credit laptop image by jedphoto from
Promoted By Zergnet



You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!