0

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?

2 Answers 2

3

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
8
  • 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, 2012 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, 2012 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, 2012 at 11:17
  • 1
    I wholeheartedly recommend Greg Wooledge's wiki: wiki.wooledge.org for all things bash.
    – adaptr
    Nov 27, 2012 at 11:23
  • question on the above code what goes the @ do (or symbolise) in the ${#hd[@]}; line?
    – twigg
    Nov 27, 2012 at 12:02
3

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).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .