if condition in bash

Hi, I have meaning to include an if condition statement in my code to check the directory for existing output files and if its existing i want the program to delete it before doing the succeeding command. i just dont know the correct syntax for it. thanks much guys, this forum has indeed been very helpful,:slight_smile:

if *.dat, *.asc exists, remove files

 
ls *.dat 1>/dev/null 2>&1 && rm -rf *.dat || echo "No Files Found"
ls *.asc 1>/dev/null 2>&1 && rm -rf *.asc || echo "No Files Found"
1 Like

Or a much safer script:

cd your_directory
ls -1d *\.dat *\.asc 2>/dev/null | while read filename
do
       # Remove echo when tested
       echo rm "${filename}"
done
1 Like

If using the if bash keyword is not a must, you could use the find program to do the job:

find . \( -name "*.dat"  -o  -name "*.asc" \) -exec rm {} \;

or

find . \( -name "*.dat"  -o  -name "*.asc" \) -delete
1 Like

Thanks guys for all the possible ways to do it. bunch of thanks everyone,:slight_smile: