tags:

views:

87

answers:

4

I have script file where a command is stored in a variable

First i got the command (assume "ls -l " command)

cmd=`cat /proc/2345/cmdline`

now doing

echo $cmd

outputs

ls -l

Now how to use $cmd to actually execute that command. which is ls -l

+6  A: 

BASH FAQ entry #50.

Ignacio Vazquez-Abrams
Vote up, excellent reference.
Anders
+1, its really nice to see an updated BASH guide available. Others were starting to stagnate.
Tim Post
+5  A: 

The simple answer is:

$cmd
Chen Levy
+2  A: 

if you have no business to store it in a variable, then don't. Just run it as usual.

cat /proc/2345/cmdline
ghostdog74
+3  A: 
eval $cmd

Just $cmd will work in many cases, but not always. See the article "Bash: Why use eval with variable expansion?" for further details.

Heinzi
Your reference makes no mention of the [evils of eval](http://mywiki.wooledge.org/BashFAQ/048).
Dennis Williamson
@Dennis: Thanks, good link. The question is: Does it apply to this case?
Heinzi
Yes, because the file `/proc/2345/cmdline` could contain something scary like `rm -rf /` (but in this case, that danger also applies to just executing `$cmd` directly).
Dennis Williamson
@Dennis: Exactly: That's not a problem of `eval` but rather a problem of the requirement, which is to blindly execute another process' command line. The question is rather: Could someone start a "harmless" process that turns into an "evil" process after "eval $cmd"-ing?
Heinzi