sean finney on 16 Sep 2010 16:40:54 -0700

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Building a command from variables in BASH


On Thu, Sep 16, 2010 at 04:26:07PM -0400, Edmond Rodriguez wrote:
> Well, I may be repeating something you covered in the links, but would
> this be a simple solution to possible issues?
> Would escaping the $'s provide a possible simple solution to a not too
> complex line, if they were serving only as variable holders and did
> not need to be resolved before the eval?

in that case you wouldn't need eval.

eval foo \$bar  

is the same as plain ol'

foo $bar

just with an extra interpretation/expansion step to get there.  this is safe
from embedded quotes and shell metacharacters, but will be problematic
if you have whitespace in the variable.  consider the following for
why it might not be desirable for the OP:

	  local i
	  while [ $# -gt 0 ]; do
	    echo "argument $i: ==$1=="
	    i=`expr $i + 1`
	args="-e 's/foo bar/far sar/g'"
	argtest $args # or eval argtest \$args if you like :)

this will pass 4 arguments to argtest instead of 2.  quoting $args would
mean only 1 argument.  to preserve that information the best way to do so
is to set the arguments as positional parameters (set+eval) and then
expand them with the special syntax "$@", which expands to each individual
parameter, quoted.  but if you're using set+eval, then you need an extra
round of escaping/quoting (basically you'd be quoting them individually
ahead of time).  that's what the articles linked in the last mail are
all about.

hypothetically i could probably conjur up a couple mad-science alternatives
to the above (lots of tempfiles, a little recursion, and some self generating
code), but i that's the stuff nightmares are made of and set+eval+"$@" is
really the way to go for a general solution.


Attachment: signature.asc
Description: Digital signature

Philadelphia Linux Users Group         --
Announcements -
General Discussion  --