I have this simple bash script to check for ~ application/x-trash files within a directory and its subdirectories.

It works fine, but it echoes empty .~ too, which seems to be harmless but annoying. How do I avoid that?


cd '/var/www/html/mypath/'
for d in $(find '/var/www/html/mypath/' -maxdepth 6 -type d)

echo $d
for f in  $d'/'*.*~; 
    do  FILE=$f;
        echo 'file to be removed:  '$FILE

For a subdirectory dir, if there is not a ~ file into dir, at the terminal I get anyway:

file to be removed: /var/www/html/mypath/../../../dir/*.*~

2 Answers 2


Assuming you just want to find any file whose name matches either *~ or .*~ (these are usually backup files left behind by an editor), then this single find invocation will do that for you:

find /var/www/html/mypath/ -type f \( -name '*~' -o -name '.*~' \) -print 

You can insert a -maxdepth 6 in there if you think it makes sense:

find /var/www/html/mypath/ -maxdepth 6 -type f \( -name '*~' -o -name '.*~' \) -print 

To delete the found files, just add -delete to the end of the command.

When the shell can not expand a filename globbing pattern to a list of names, it is retained as an unexpanded pattern. This is why you get the result you get with your code.

  • Yes, thanks. Do you happen to know if there is a way to fix my code too, say something like: for f in $d'/'\( -name '*~' -o -name '.*~' \);?
    – mario
    Aug 19, 2017 at 20:06
  • @mario The find in my answer replaces the two for loops in your code, thereby fixing it. For your second loop to ignore printing unexpanded patterns, you would have to compare the value of $FILE to that of the pattern for equality, and also make sure there is no file with that name.
    – Kusalananda
    Aug 19, 2017 at 20:14

the following does what I need:


cd '/var/www/html/mypath/'

for i in `find '/var/www/html/mypath/' \( -name '*~' -o -name '.*~' \) -type f`; do

    echo 'file to be removed:  '$i
    mv $i   '/var/www/html/trashTest'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .