Operating System - HP-UX
1834141 Members
1967 Online
110064 Solutions
New Discussion

Test for existence before deleting

 
SOLVED
Go to solution
Ed Hon
Regular Advisor

Test for existence before deleting

From a script I want to delete all files of a certain extension, only if at least one of those files exists. For example, I want to execute "rm *.ABC", only if there is at least one file of extension .ABC . (I'm trying to avoid generating the message "rm: *.ABC non-existent".) Thanks.
3 REPLIES 3
Thierry Poels_1
Honored Contributor

Re: Test for existence before deleting

Hi,

rm *.ABC > /dev/null 2>&1

this will remove the specified files, and redirect all standard and error output to /dev/null.
Not exactly what you asked, but anyway ;-)

regards,
Thierry.
All unix flavours are exactly the same . . . . . . . . . . for end users anyway.
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Test for existence before deleting

Hi:

Don't bother, just do a rm -f *.ABC. Man rm for details.

Clay
If it ain't broke, I can fix that.
Darrell Allen
Honored Contributor

Re: Test for existence before deleting

Hi Ed,

Clay gives you the best answer for suppressing error messages for rm but in case you still want to know if you have at least one file ending in .abc you could try either of the following:

if [ -f *.ABC -o -f .*.ABC ]
then
echo have some
fi

ls *.ABC .*.ABC >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo have some
fi

The above also handle hidden files such as:
..abc .a.abc .abc
and will skip files such as:
.aabc a.aabc

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)