简体   繁体   中英

Bash grep output in addition to echo within if statement

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM