Tux

...making Linux just a little more fun!

Hi, I have one doubt

k.Ravikishore [ravikishore.k at hclsystems.in]
Sat, 23 Sep 2006 16:35:28 +0530

How to create a bash shell script that removes all files whose names end with a "~" from your home directory and subdirectories.

----------------------------- HCL Systems, Hyderabad, India


Top    Back


Lew Pitcher [lpitcher at sympatico.ca]
Sat, 23 Sep 2006 07:53:13 -0400

On Saturday 23 September 2006 07:05, k.Ravikishore wrote:

> 
> How to create a bash shell script that removes all files whose names end
> with a "~" from your home directory and subdirectories. 

If you take it in steps, then it isn't too much of a problem.

First, think of how you would express the filename of the files you want to delete. Does "all files" include "dot files" (i.e. .config~ )? It will make a difference. With regular globbing, bash excludes dotted files from the * match.

With regular globbing, the regular expression

  *~
will match all non-dotted filenames that end with a tilde, while
  .*~
will match all dotted filenames that end with with a tilde

Now that we've got the name figured out, how do we find it. Well, one way is to use the find(1) program ("man 1 find" for details). The find(1) program takes a list of directories to search, a list of conditions to be met, and a list of actions to execute. It searches the given list of directories for files and directories that match the given list of conditions, and if a match is detected, it executes the given list of actions. One possible action is to delete the matching file or directory. For example find /home/myhome -name somename -exec rm -f {} \; will search the directory /home/myhome (and all subdirectories under it) for a file or directory named "somename", and if such a file or directory is found, find will execute the rm command on that file, deleting it.

For you, you want something like

  find /home/yourhome -name '*~' -exec rm -f {} \;
Since you can use environment variables (you'll run this as a bash script, after all), you can use the $HOME envvir to name your home directory. Now the command looks like
  find $HOME -name '*~' -exec rm -f {} \;
Let's put this all together in a script
  #!/bin/bash
  find $HOME \( -name '.*~' -o -name '*~ \) -exec rm -f {} \;
Done!

-- 
Lew Pitcher


Top    Back