How Do I Make a Bash Script To Find Unused Images in a Project? How Do I Make a Bash Script To Find Unused Images in a Project? shell shell

How Do I Make a Bash Script To Find Unused Images in a Project?


With drysdam's help, I created this Bash script, which I call orphancheck.sh and call with "./orphancheck.sh myfolder".

#!/bin/bashMYPATH=$1find "$MYPATH" -name *.jpg -exec basename {} \; > /tmp/patternsfind "$MYPATH" -name *.png -exec basename {} \; >> /tmp/patternsfind "$MYPATH" -name *.gif -exec basename {} \; >> /tmp/patternsfor p in $(cat /tmp/patterns); do    grep -R $p "$MYPATH" > /dev/null || echo $p;done


I'm a little late to the party (I found this page while looking for the answer myself), but in case it's useful to someone, here is a slightly modified version that returns the path with the filename (and searches for a few more file types):

#!/bin/bashif [ $# -eq 0 ]  then    echo "Please supply path to search under"    exit 1fiMYPATH=$1find "$MYPATH" -name *.jpg > /tmp/patternsfind "$MYPATH" -name *.png >> /tmp/patternsfind "$MYPATH" -name *.gif >> /tmp/patternsfind "$MYPATH" -name *.js >> /tmp/patternsfind "$MYPATH" -name *.php >> /tmp/patternsfor p in $(cat /tmp/patterns); do    f=$(basename $p);    grep -R $f "$MYPATH" > /dev/null || echo $p;done

It's important to note, though, that you can get false positives just looking at the code statically like this, because code might dynamically create a filename that is then referenced (and expected to exist). So if you blindly delete all files whose paths are returned by this script, without some knowledge of your project, you might regret it.


ls -R *jpg *gif *png | xargs basename > /tmp/patternsgrep -f /tmp/patterns *html

The first line (recursively--your problem is ill-specified, so I thought I'd be a little general) finds all images and strips off the directory portion using basename. Save that in a list of patterns. Then grep using that list in all the html files.