I generated multiple script.txt in multiple directories for different subjects. Now I need to check if all the script.txts contain string ” finished without error”. If yes, returned ok; if no, returned parents directory, so that I knew which subject went wrong.
for i in *
do
if grep "$finished without error" $i; then
echo "ok"
else
echo $parentdir
fi
done
It was fine when I checked in subdirectories where I stored the text file. However, when I directed to main directory of subjects, it gave me error.
Advertisement
Answer
for i in * will only process the files under the directory where your script is called from. It will not go down directories recursively.
If you want to process the current directory, and all sub-directories, you should use find to do such a task. Like this:
find . -type f -exec grep -L "finished without error" {} ;
This will return a list of all files that do not contain finished without error.
Details:
find .: will run the find on the current directory (.)-type f: will only perform the action on files. Directories are traversed, but the grep will not be attempted on those.-exec SOMETHING ;: will execute SOMETHING for each file that matches thefindcondition. Here the only one is-type f. So it will execute SOMETHING for each file.;is to letfindthat the arguments to-execare complete.- Here SOMETHING is:
grep -L "finished without error" {}.-Lofgreplists the filename if the search does not find what you searched for.{}tells thefindcommand to execute thegrepcommand on the current file it found.
So it will traverse your directories, find each file and run the grep on each of those files. grep will output the filenames that do not contain the text.
For your script, you can put your code in https://www.shellcheck.net/, it will let you know your syntax errors and propose solutions. Like $finished should probably not have the $ in there. I guess it is simple text. Unless you have a $finished variable defined somewhere, but in the code you put here, it is not initialized. Same for $parentdir