bashterminal

Bash script to delete a particular file


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

Solution

  • There are a few relatively elegant options available to you.

    One would be to wrap rm in a function that checks if there are any files of the type you want to delete in your folder. You could use ls to check if there are any files matching your wildcard, as per this question:

    #!/usr/bin/env bash
    
    rm_check() {
        if ls *."${1}" 1> /dev/null 2>&1; then
            rm *."${1}"
            echo "All *.${1} files have been deleted"
        else
            echo "No *.${1} files were found"
        fi
    }
    
    read -p "are you sure you want to delete the files? Y/N " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        rm_check torrent
        rm_check zip 
        rm_check deb
    fi
    

    This version is nice because it has everything laid out the way you originally planned.

    A cleaner version, in my opinion, would be one that only looked at files that matched your pattern to begin with. As I suggested in the comments, you could do it with a single find command:

    #!/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
        find -name '*.torrent' -o -name '*.zip' -o -name '*.deb' -delete
        echo "all those files have been deleted............."
    fi
    

    This method makes your script very short. The only possible disadvantage of this method for your purpose is that it will not report which file types are missing.