Ubuntu – remove file but exclude all files in a list

bashcommand linermscripts

I need to cleanup a folder periodically.
I get a filelist which contains text, which files are allowed.
Now I have to delete all files which are not in this file.

Example:

dont-delete.txt:

dontdeletethisfile.txt
reallyimportantfile.txt
neverdeletethis.txt
important.txt

My folder do clean-up contains this as example:

ls /home/me/myfolder2tocleanup/:

dontdeletethisfile.txt
reallyimportantfile.txt
neverdeletethis.txt
important.txt
this-can-be-deleted.txt
also-waste.txt
never-used-it.txt

So this files should be deleted:

this-can-be-deleted.txt
also-waste.txt
never-used-it.txt

I search something to create a delete command with an option to exclude some files provided by file.

Best Answer

The rm command is commented out so that you can check and verify that it's working as needed. Then just un-comment that line.

The check directory section will ensure you don't accidentally run the script from the wrong directory and clobber the wrong files.

You can remove the echo deleting line to run silently.

#!/bin/bash

cd /home/me/myfolder2tocleanup/

# Exit if the directory isn't found.
if (($?>0)); then
    echo "Can't find work dir... exiting"
    exit
fi

for i in *; do
    if ! grep -qxFe "$i" filelist.txt; then
        echo "Deleting: $i"
        # the next line is commented out.  Test it.  Then uncomment to removed the files
        # rm "$i"
    fi
done