[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] eval backgrounds with & in variable string
From: |
Eduardo A . Bustamante López |
Subject: |
Re: [Help-bash] eval backgrounds with & in variable string |
Date: |
Fri, 14 Mar 2014 13:05:58 -0700 |
User-agent: |
Mutt/1.5.21 (2010-09-15) |
On Fri, Mar 14, 2014 at 12:29:28PM -0700, Jesse Molina wrote:
>
> Behold my glory:
>
> [~/work/eval_testing]
> address@hidden>eval echo 'one&uno&ichi'
> [3] 14201
> [4] 14202
> one
> -bash: uno: command not found
> -bash: ichi: command not found
> [3] Done echo one
> [4] Exit 127 uno
>
>
>
>
> Okay, that's definitely not what I wanted. Eval seems to have
> evaluated my "&" characters into being a split and then tries to
> background those commands.
Yes, as expected.
>
> Can I "set" something to make this work, or am I going to have to
> escape these on input?
Yes: echo 'one&uno&ichi' # this works
if you want to use variables:
string='one&uno&ichi'; echo "$string"
if you want to use user input:
IFS= read -r -p 'Provide string> ' string; echo "$string"
I cannot think of a reason why you would want to use eval there.
Consider that eval takes a string and evaluates it as code. So, if
you have:
eval echo 'one&uno&ichi'
by shell parsing rules, that line will become the following words:
['eval', 'echo', 'one&uno&ichi'] # note that the quotes aren't really
there, it's just to denote the
start and end of the word in my
representation of the vector of
words.
So bash takes the first word as a command, and since it's the built
in 'eval', it'll *again* interpret the rest of the arguments,
apparently concatenated to a single string, so it becomes:
background(['echo', 'one']); background(['uno']); ['ichi'];
by shell parsing rules. If you want to avoid this, then you'll have
to put a whole new layer of quotes, so that the second evaluations
takes the inner quotes, which are not used by the first evaluation,
like this:
eval echo '"one&uno&ichi"'
which becomes:
['eval', 'echo', '"one&uno&ichi"']
and then ['echo', 'one&uno&ichi']
But, again, why are you using eval here?
>
>
>
> While on the subject of eval, does anyone else have fun examples,
> known pitfalls, and other interesting things?
Well, there's nothing fun in using eval. It's just a way of using
data as code, which is a recipe for disaster (improper escaping will
lead to code injection, the nested quotes are hard to get, you're
introducing unnecessary overhead, and so on).
--
Eduardo Alan Bustamante López