how to store a command in a variable
Hiiiiiiiii,
Well, everybody knows the output of Code:
ls Code:
var=ls The problem occurs when we try to pipeline it. Consider the following problem: Code:
ls | grep * Code:
var="ls|grep *" |
EDIT: The following is NOT what you're looking for:
Code:
var=`ls|grep *` |
Quote:
Code:
ls|grep * |
Code:
var='ls|grep *' With backtics you get the complete output from running the command. |
Quote:
Code:
eval $var |
And to use literal asterisks escape them using a backslash, e.g.
Code:
CMD='grep \* testfile' |
Gah!
Eval is a common misspelling of "evil". Don't use it if you don't know what you are doing, and even then it's probably a sign that you're Doing Something Wrong. This topic has been covered by BashFAQ in depth: http://mywiki.wooledge.org/BashFAQ/050 Also, what is it you're really trying to do? I really can't seriously think that it's an ls+grep, but if it is, you shouldn't try to do anything with the output of ls. Parsing ls is *extremely* error-prone. |
Quote:
|
Not really. Slip up just a little bit and you've got a vulnerability, and there's lots of hidden gotchas in using eval. Word splitting is only the beginning of how things can go badly. Every time I need to write an eval, I triple-check, and then check it 3 more times while I'm sleeping every night. Almost every time you think about reaching for eval, seriously consider if you need to change your approach.
http://mywiki.wooledge.org/BashFAQ/048 |
Quote:
Code:
rm `find . -name '*~'` |
The reason for the ranting about eval is because of how much is now "outsider's text". With $(), it's easy to see what you're executing and there's no possibility of any strange results. With eval, depending on how paranoidly it's constructed, you can easily cause the one who used eval to run something they didn't expect by perhaps creating a file with an interesting filename in /tmp.
Using eval safely requires extreme levels of paranoia, and if you're that paranoid, you're going to just avoid it entirely because you can't be paranoid enough to completely guarantee bad things from happening. |
Quote:
Edit: Applying a sed command with variables inside double quotes could prove even more complicated (although still simple) or more delicate than using eval. |
All times are GMT -5. The time now is 04:25 PM. |