Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Execute String as a Unix Command

 
Sujoy Choudhury
Ranch Hand
Posts: 136
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Linux/Unix Gurus,

I have a typical requirement:
1. I have a file where I kept all the commands in each line like key=value
eg.



2. Then I loop through this file like below:




3. Now the command is getting read from the file nicely but I can't execute that command. I tried using eval/$/another ``/" " sign and what not.

Thanks,
 
Peter Johnson
author
Bartender
Posts: 5852
7
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not simply this:

$COMMAND

In other words, this should work:

$CMD="ls -al"
$CMD
 
Sujoy Choudhury
Ranch Hand
Posts: 136
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter,
Thanks for your reply.

If you see the statement
echo "Command="$COMMAND
This should have executed the command right?
But it is not.

I am really confused.
 
Tim Holloway
Saloon Keeper
Posts: 18303
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "echo" command takes whatever text follows it on the command line and displays it on stdout. It does not execute that text.

Please remember that permitting an arbitrary string to be executed as a command is not something to do casually. When done in the wrong place at the wrong time, it can be used as a security exploit.
 
Sujoy Choudhury
Ranch Hand
Posts: 136
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tim,
Yes, I got your security point. And I have seen that too in my code if I load the file and get the values using $KEY sign, the command gets executed at that point of time which I don't want to.
That's why I changed my code and 'grep'ing line by line to read the values.
But in this approach I can't execute the value as a Unix command.
Is this doable or I am doing something very wrong?

Thanks,
 
Sujoy Choudhury
Ranch Hand
Posts: 136
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Found the answer here
http://www.unix.com/shell-programming-scripting/139327-execute-command-stored-string.html

anyway thanks a lot guys for reading this post...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic