what is the real usage of eval in shell scripting
whats the difference between
$ cmd
&&
eval cmd
what is the real usage of eval in shell scripting
whats the difference between
$ cmd
&&
eval cmd
eval is useful when cmd contains something which needs to be evaluated by the shell. The typical case would be when you have a variable containing the index of an argument you want to access.
n=1 # or whatever, just to make this self-contained
eval echo \${$n}
Search these forums for examples; some of them are rather elaborate.
but whats the difference if i write
echo $($n) instead of
eval echo \${$n}
Experiment to see.
vnix$ n=1
vnix$ echo $($n)
bash: 1: command not found
vnix$ n="date"
vnix$ echo $($n)
Wed May 21 20:39:00 EEST 2008
So it uses the value of $n as a command. (It's the same as echo `$n` with backticks.)
Contrast:
vnix$ set -- one two three # sets $1 $2 $3
vnix$ echo $1
one
vnix$ n=1
vnix$ echo ${$n} # attempt to echo $1
bash: ${$n}: bad substitution
vnix$ eval echo \${$n}
one
See? Now if you assign n=2 it will echo the value of $2, etc. So you can change the name of the variable you are referring to programmatically, dynamically.
This is an advanced topic; if you don't have a use for it, don't bother. If you really want to understand this, I suggest you play around with set -x and try different things until you understand what's going on.
thanks its convincing and clear ..
thanks for the help
is there any way to include or import one script into other
like application programs
Include as in..? You can call one script from the other. That can work.
You should probably start a new thread for an unrelated question anyway.
/bin/sh$ var=foo
/bin/sh$ foo=bar
/bin/sh$ eval echo \${$var}
bar
/bin/sh$ val=`eval echo \${$var}`
bad substitution
How can I save the output of eval echo \${$var} to a variable?
Thanks.
Maybe something like this:
$ var=foo
$ foo=bar
$ set -x
$ cmd='eval echo \${$var}'
+ cmd='eval echo \${$var}'
$ val=$(eval $cmd)
++ eval eval echo '\${$var}'
+++ eval echo '${foo}'
++++ echo bar
+ val=bar
$ echo $val
+ echo bar
bar
That works for Korn shell, but I was looking for a Bourne shell solution.
---------- Post updated at 01:24 PM ---------- Previous update was at 01:11 PM ----------
/bin/sh$ var=foo
/bin/sh$ foo=bar
/bin/sh$ val=`eval echo \\$\${var}`
/bin/sh$ echo ${val}
bar
Thank you Ken!