Tuesday, January 22, 2013

How to Write a Shell Script to Delete Files



1. 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.'

2. 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.

3. 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 $*'.

4. 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.

5. 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.

6. 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.

No comments:

Post a Comment