We all like to keep things tidy, right? We’ve all see old functions in our code that are go unused, it’s a common byproduct of refactoring and maintaining code, it happens!
Recently I’ve had to maintain a few tutorials and workshops which of course have plenty of images referenced in the documentation. The same thing happened, steps were changed and images went unused.
Rather than manually search each file we can use a few simple bash commands to mark them all as deleted. See the bash script below as an example, save it to a file and run it locally from your project root.
imagepaths=$(find . -name '*.jpg' -o -name '*.jpeg' -o -name '*.png') counter=0 for imagepath in $imagepaths; do filename=$(basename -- $imagepath) if ! grep -q -r --exclude-dir=".git" $filename .; then git rm $imagepath counter=$((counter+1)) fi done if [ "$counter" -eq "0" ]; then echo "No images were removed!" else echo "Removed a total $counter images, w00t!" fi
The script looks for images with a PNG, JPEG, and JPG extention using
find, you can easily add other file extensions here. Then uses
grep to see if the file is used anywhere in the project, ignoring the
.git directory (I decided to just used the filename, you can choose to use the whole path). Lastly, it marks them for deletion using
git rm. The counter is for fun :shrug:.
You can even add some additional logic like:
git pull origin master git checkout -b rm_images
before and after the script to push your changes more quickly.
git commit -m "remove unused images" git push origin rm_images
Now, should I try to turn this into a GitHub App?