removing mutiple files

I have a script which removes files (if they exist)
Here is a cut down example of the script.
Variables file1,file2 etc have already been initialized

#!/bin/bash
if [ -f $file1 ]
then
\rm file1
fi
if [ -f $file2 ]
then
\rm file2
fi
if [ -f $file3 ]
then
\rm file3
fi
if [ -f $file4 ]
then
\rm file4
fi
if [ -f $file5 ]
then
\rm file5
fi
if [ -f $file6 ]
then
\rm file6
fi

.........and so on

Is there a simpler way to do this??

How about this ?

for list in file1, file2, file3
if [ -f $list ] ; then
rm -f $list
fi;

Havnt tested it though.

Vino

for list in $file1 $file2 $file3; do
[ -f $list ] && \rm $list 
done

Reborg,

In you post,

why the $list1 , $list2 in

for list in $file1 $file2 $file3; do

and not

for list in file1 file2 file3; do

Isnt $list supposed to have whatever file1 holds and so on and so forth ?

My variation on all this would be....

$ cat > rmlist
file1
file2
file3
file4
file5
file6
^D
$ while read filename; do
>   [ -f $filename ] && \rm -f $filename
> done < rmlist
$

while loops process faster than for loops...

Cheers
ZB

Because I read his first post which said he already had initialized the filenames elsewhere in his script, from his post I had no way of knowing if they were used for other things previous to being removed and thus though it better to use his preexsisting variables.

here's my version ...

skip the file exists check and just throw the file not found error to /dev/null ...

rm -f $file1 $file2 $file3 $file4 ... 2> /dev/null

or ... if you have the file list like what zazzy has ...

rm -f `< rmlist` 2> /dev/null

Try...

for i in 1 2 3 4 5 6; do eval [ -f \$file$i ] && echo rm \$file$i; done
list="file1 file2 file3 file4 file5 file6"
rm -f `echo $list` 2>/dev/null

or even

list="file1 file2 file3 file4 file5 file6"
rm -f $list 2>/dev/null

:slight_smile: