Bash For Loop Help

This is a short program I wrote to search through a directory and move files containing the keyword to a folder.

#!/bin/bash

echo 'What is the directory?'
read DIR
echo -e '\n'

echo 'What is the keyword?'
read KEY

echo -e '\n'

cd $DIR
rmdir 'relevant_files'
mkdir 'relevant_files'

for entry in 'grep -ilr $KEY $DIR'; do
    echo $entry
    mv $entry 'relevant_files'
done

The main problem I'm having with is the for loop.

for entry in 'grep -il $KEY $DIR'; do
    echo $entry
    mv $entry 'relevant_files'
done

My question is, how would I make the for loop entries equal to each file grep comes up with in the directory?

No need to use grep . Use wildcards * or ? to perform expansion referred as globbing:

for entry in ${KEY}* ; do
    echo "$entry"
    mv "$entry" relevant_files/
done

I'm not searching for a filename, I'm searching for text within the file. Sorry for explaining poorly.

for file in *
do
        if grep "$KEY" "$file" 1> /dev/null 2> /dev/null
        then
                echo "$file"
                mv "$file" relevant_files/
        fi
done
1 Like

I usually prefer:

        if grep -q "$KEY" "$file"

instead of:

        if grep "$KEY" "$file" 1> /dev/null 2> /dev/null

because I want to see diagnostic messages if one or more of the files being processed can't be opened for reading, or have been renamed or deleted by something else while this script is also processing files in this directory.

You want to mv all files that contain a certain key, you want to do it recursively, and you want to know the filenames moved? Try

 mv -v  $(grep -ril "$KEY" *) relevant_files/

Nor for loop nor echo required.