Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to delete a particular file

Tags:

bash

terminal

I am working on this bash script that is supposed to delete files with a particular extension and I don't want it to return a no such file or directory output when I check if those files still exist. Instead, I want it to return a custom message like: "you have already removed the files". here is the script:

#!/usr/bin/env bash
read -p "are you sure you want to delete the files? Y/N " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
  rm *.torrent
  rm *.zip 
  rm *.deb
echo "all those files have been deleted............."
fi
like image 693
mots Avatar asked Aug 06 '26 08:08

mots


1 Answers

You could do like this:

rm *.torrent *.zip *.deb 2>/dev/null \
&& echo "all those files have been deleted............." \
|| echo "you have already removed the files"

This will work as expected when all files exist, and when none of them exist.

You didn't mention what to do if some of them exist but not all. For example there are some .torrent files but there are no .zip files.

To add a third case, where only some of the files were there (and now removed), you would need to check the exit code of the removal for each file type, and produce the report based on that.

Here's one way to do that:

rm *.torrent 2>/dev/null && t=0 || t=1
rm *.zip 2>/dev/null && z=0 || z=1
rm *.deb 2>/dev/null && d=0 || d=1

case $t$z$d in
  000)
    echo "all those files have been deleted............." ;;
  111)
    echo "you have already removed the files" ;;
  *)
    echo "you have already removed some of the files, and now all are removed" ;;
esac
like image 87
janos Avatar answered Aug 09 '26 01:08

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!