Issue
the following code is to find files using grep, and then copy them into a new folder with a new name(found_file1 found_file2 etc.).
It works when search(){...} is removed and the program is run as is. But when put into a function, it deletes-creates the Found folder but fails to create the files into it.
#!/bin/bash
search(){
founddir=$(pwd)/Found
#---------gets inputs
echo "Enter the name of the directory:"
read searchdir
echo "Enter the keyword: "
read keyword
#-----this if statement checks if there are matching files
if grep -q -lr $keyword "$(pwd)/$searchdir"
then
rm -rf Found
#removes old Found file, we're running this over and over it becomes more convinient to automate it this way. will be removed later
mkdir Found
#creates found file folder
grep -q -lr $keyword "$(pwd)/$searchdir" | while read -r dir ; do
#------creates filepath to use in touch command, UNCERTAIN if it manages to
file="$founddir/found_$(basename $dir)"
enter code here
#should create a file but does not
touch $file
#cant cp contents because file is not created
cp -p $dir $file
done
echo "Files were copied to the Found directory!"
else
echo "Keyword not found in files!"
fi
}
search
we have tried putting/removing quotes from variable declerations, but it did not seem to help.
Solution
I'm not sure what your function should do but your i think your problem is in this line:
grep -q -lr $keyword "$(pwd)/$searchdir" | while read -r dir ; do
-q
does not return anything but exit code. so in this case when you are piping output of grep
to while
loop, there is nothing for while
to do.
what you might need to do is to remove -q
from the grep so it will return files names for while
to set for dir
variable in your loop and do the rest.
Answered By - Yaser Kalali Answer Checked By - Mildred Charles (WPSolving Admin)