1

I have a simple script that checks if images are being used within our html directory. I have a file called imageserver.txt which looks like:

imageserver/icons/socialmedia/sqcolor_tumblr.png
imageserver/icons/socialmedia/sqcolor_gaf.png
imageserver/icons/socialmedia/sqcolor_yelp.png
imageserver/icons/socialmedia/sqcolor_linkedin.png
.....  

This is my simple script

imageSearch.sh

#!/bin/bash

while IFS= read -r var
do

echo "\n ... Searching for $var \n"

if grep -rq $var /var/www/html; then

    echo "Image exists ...\n"
    echo $var >> doesExist.txt

else

    echo "Image does not exist ...\n"
    echo $var >> nonExists.txt

fi

done < ./imageserver.txt

Now, this works GREAT. I am wanting to add one more element only to the if statement. I want the echo >> to not only print $var to the doesExist.txt -- But what file it was found in .. I am thinking I may need a secondary grep inside the if?

My desired input into doesExist.txt would look like:

imageserver/icons/socialmedia/sqcolor_tumblr.png  |  /var/www/html/file1.html
imageserver/icons/socialmedia/sqcolor_tumblr.png  |  /var/www/html/file2.html

I am stuck and not quite sure if I need a secondary grep or -- Is it possible I can get the file names from the original grep within the original if statement?

How do I accomplish my desired input into doesExist.txt

1 Answer 1

3

Change:

if grep -rq $var /var/www/html; then

    echo "Image exists ...\n"
    echo $var >> doesExist.txt

to some variation of:

results=$(grep -rH "$var" /var/www/html)
if [ $? -eq 0 ]; then

    echo "Image exists ...\n"
    echo "$results" >> doesExist.txt
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent -- I replaced the -H (--with-filename) with -l ( --files-with-matches) and double bracketed the if solved! Thanks so much for your help!
in addition ... The if [[ $? is a lifesaver .. I probably never would have come across that just researching this specific problem-- Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.