Bash – How to add a variable into a grep command

bashshellshell-scripting

I'm running the following grep command

var=`grep -n "keyword" /var/www/test/testfile.txt`

This work just as expected but I need to insert the file name dynamically from a loop like so:

var=`grep -n "keyword" /var/www/test/`basename ${hd[$i]}`.txt`

But obviously the use of ` brakes this with a unexpected EOF while looking for matching “' and unexpected end of file

Any ideas of away around this?

Best Answer

Please don't use `, and use a function:

mygrep() { grep -n "yourkeyword" "/var/www/test/${1##*/}.txt"; }
for (( i= 0; i < ${#hd[@]}; i++ )); do yourvar=$(mygrep "${hd[$i]}"); done