eval | eval y='$'$x | How to execute shell command produced using echo ? eval "$(echo "mv ...")"
1) foo=10 x=foo
2) y='$'$x
3) echo $y
4) $foo
5) eval y='$'$x
6) echo $y
7) 10
- In the first line you define
$foo
with the value'10'
and$x
with the value'foo'
. - Now define
$y
, which consists of the string'$foo'
. The dollar sign must be escaped with'$'
. - To check the result,
echo $y
. - The result will be the string
'$foo'
- Now we repeat the assignment with
eval
. It will first evaluate$x
to the string'foo'
. Now we have the statementy=$foo
which will get evaluated toy=10
. - The result of
echo $y
is now the value'10'
.
=============
How to execute shell command produced using echo ?
I have tried doing:
echo " mv /server/today/logfile1 /nfs/logs/ && gzip /nfs/logs/logfile1" | sed 's|logfile1|logfile2|g'
It printed:
mv /server/today/logfile2 /nfs/logs/ && gzip /nfs/logs/logfile2
You could pipe your command into a shell so it gets executed:
echo "mv ..." | bash
Or you could pass it as an argument to a shell:
bash -c "$(echo "mv ...")"
Or you could use the bash built-in
eval
:eval "$(echo "mv ...")"
ubu1404@ubuntu1404lb01:~/t$ eval $(echo "touch file")
ubu1404@ubuntu1404lb01:~/t$ ll
-rw-rw-r-- 1 ubu1404 ubu1404 0 Mar 8 14:07 file
Comments
Post a Comment