Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to use grep to color some log files . I wrote a script and a part of it looks like this :

#!/bin/bash
com="GREP_COLOR=\"1;36\" egrep --color=always  '[^a-zA-Z0-9]' $log |less -R"
log="/var/log/syslog"
eval $com

The execution was missing $log !

I tried this :

#!/bin/bash
com="`GREP_COLOR=\"1;36\" egrep --color=always  '[^a-zA-Z0-9]' $log |less -R`"
log="/var/log/syslog"
eval $com

Nothing happened !

Could you see any mistake in my code ?

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

Do not use eval.

Right here it simply could be avoided:

function color_log() {
  log=$1
  GREP_COLOR="1;36" egrep --color=always '[^a-zA-Z0-9]' $log | less -R
}

color_log "/var/log/syslog"
share|improve this answer
    
Can you summarize the punch line of your link for "Do not use eval"? It is not that obvious. –  Bernhard Oct 20 '13 at 17:11
    
There are many cases (and this one is one of them) when eval could be simply substituted with something else which helps you to ignore all that redundant checks and thoughts about security issues and safety. –  ДМИТРИЙ МАЛИКОВ Oct 20 '13 at 17:13
    
Your code isn't equivalent to the OP one. You should set the GREP_COLOR variable before the egrep command, on the same line. –  jlliagre Oct 20 '13 at 19:20
    
@jlliagre fixed, thanks –  ДМИТРИЙ МАЛИКОВ Oct 20 '13 at 19:21
add comment

You need to escape the $ in $log in your first script:

#!/bin/bash
com="GREP_COLOR=\"1;36\" egrep --color=always  '[^a-zA-Z0-9]' \$log |less -R"
log="/var/log/syslog"
eval $com

Edit:

There is indeed no need to use eval in this particular case so suggesting an alternative and safer way like ДМИТРИЙ did is definitely preferred. On the other hand, while the design error was to use eval in the first place, the coding error which I addressed was not to quote $log. While eval definitely has a justified bad press because of all vulnerabilities associated with it, it is nevertheless a very powerful instruction that is worth knowing. Carefully written evals can avoid malicious or unexpected code execution.

share|improve this answer
    
Sure, you can get it to work, but this horrible misuse of eval should not go uncorrected. –  Gilles Oct 21 '13 at 16:06
    
@Gilles Indeed, I even help the accepted answer to be correct. Updating my own answer to make clear I was addressing the coding error but not the design one. –  jlliagre Oct 21 '13 at 16:45
add comment

Your Answer

 
discard

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.