![]() |
| ||
| Dynamically-created shell commands I am trying to dynamically create some shell script and run it (but don't know how!). I want to read in a string from a file (e.g. ' echo $myvar') then run that string (and, yes, myvar IS an existing variable). Can it be done? I have thought about writing it off to a .sh file and executing the file, but I can't get that to work either. To put the problem into context, I want to read in a bunch of commands from a file and run them, and they may contain names of existing variables. Incidentally, I'm using bash, but a general solution will be fine. |
| ||
| Re: Dynamically-created shell commands Hi Jaoqua! How have you tried so far? Depending on how the file is formatted (are there spaces in some of the commands you want to run?) it should be as simple as: for i in $(cat /path/to/file); do $i; done If there are spaces in the command lines that you want to run, it'll get a little more complicated. You'd have to do something like this to change the Internal Field Separator temporarily, or else each line will be broken into a new command at every space: cat /path/to/file |while IFS= read command; do I hope this helps! -G |
| ||
| Re: Dynamically-created shell commands G, Thanks for your answer. It gets part of the job done, but unfortunately not all of it. An example input file to my script might be... echo Started If you give this a go with your code you'll see that the echos are fine, but the variables aren't processed properly. I'm stumped! Help! |
| ||
| Re: Dynamically-created shell commands Okay, I think I'm confused now. It sounds like you just need to run that file as a shell script. # sh ./file Unless there's a reason to run it line-by-line... If you can't run it in place like the above example, you might want to copy it off to another file and execute it there. To do it using our original example: [code] cat /path/to/file |while IFS= read command; do echo "$command" done > /tmp/script.sh sh /tmp/script.sh [code] I'm not sure if you can run it line by line. I was originally thinking you were using stand-alone commands, instead of running multiple commands together and setting variables. Hope this helps! -G |
| ||||
| Re: Dynamically-created shell commands Yes, It would make more sense to just run it in a tmp script. The reason only the echo's work in the "while read" loop is that you're processing one line at a time, and not maintaining state between them, so the lines Quote:
if you just "run" each line, your Quote:
Quote:
Quote:
I'd say go with Gromit's suggestion above to encounter minimum hassle Best wishes, Mike |
| All times are GMT -4. The time now is 1:47 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC