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
  1. In the first line you define $foo with the value '10' and $x with the value 'foo'.
  2. Now define $y, which consists of the string '$foo'. The dollar sign must be escaped with '$'.
  3. To check the result, echo $y.
  4. The result will be the string '$foo'
  5. Now we repeat the assignment with eval. It will first evaluate $x to the string 'foo'. Now we have the statement y=$foo which will get evaluated to y=10.
  6. 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

Popular posts from this blog

HAproxy logging

tomcat catalina coyote jasper cluster

NFS mount add in fstab _netdev instead of default | firewall-cmd --list-all