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

which is a bash command. How can I make it get executed, instead of just printing it?

  • 1
    I tried to answer your question as formulated, but it's not obvious to me how this is useful; are you actually trying to accomplish something more complicated? – dhag Nov 20 '15 at 14:42
  • @dhag and upvoter Yes it will help me to move log files with out using side keys. – rɑːdʒɑ Nov 20 '15 at 14:47
  • @dhag my initial question is unix.stackexchange.com/questions/243317/… but at comment given for answer I have mentioned my problem. I am trying to solve it but stuck here.... If you still want more information why I need to get this. – rɑːdʒɑ Nov 20 '15 at 14:51
  • Is your actual problem that you have a bunch of files within /server/today/, and that you would like to move and gzip all of them? If so, I will suggest a simpler / safer solution. – dhag Nov 20 '15 at 14:55
  • @dhag please go on – rɑːdʒɑ Nov 20 '15 at 16:42

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 ...")"

Note, however, that all of those code-generating commands look a bit brittle to me (there are ways they will fail as soon as some of the paths contain spaces, etc.).


You're reimplementing history substitution.

$ mv /server/today/logfile1 /nfs/logs/ && gzip /nfs/logs/logfile1
$ !!:gs/logfile1/logfile2

If you haven't actually executed the first command yet, and just want to execute a set of similar commands, consider a loop:

for f in logfile logfile2; do
    mv /server/today/"$f" /nfs/logs && gzip /nfs/logs/"$f"
  • I have similar script that does same as your 2nd script do but the 1st one is impressive . Thank you. – rɑːdʒɑ Nov 21 '15 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.