Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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
share|improve this answer
FGS? A little harsh. Sorry I was only asking im new to BASH/Shell give me a chance to learn that's why I ask –  twigg Nov 27 '12 at 10:39
Fair enough: the use of backticks (`) to execute commands is discouraged and has been deprecated for many years now; $() is cleaner and offers less surprises, plus it is easier to quote and nest. –  adaptr Nov 27 '12 at 11:13
thank you, I have only learnt from reading other peoples code, I guess doing this may not be the best way as the code could be old, like in this case, lesson learnt. –  twigg Nov 27 '12 at 11:17
I wholeheartedly recommend Greg Wooledge's wiki: wiki.wooledge.org for all things bash. –  adaptr Nov 27 '12 at 11:23
thanks for the link –  twigg Nov 27 '12 at 11:57

You can also use:

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

(observe the quotings, and, as adaptr mentioned, don't use backticks, but $(...) instead, as it's nestable).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.