5

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?

dhag
  • 15,440
  • 4
  • 54
  • 65
Raja G
  • 5,749
  • 12
  • 44
  • 67
  • 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. – Raja G Nov 20 '15 at 14:47
  • @dhag my initial question is http://unix.stackexchange.com/questions/243317/bash-how-can-i-replace-a-string-in-a-previous-command 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. – Raja G 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 – Raja G Nov 20 '15 at 16:42
  • You'll get better answers when you tell _why_ you're trying to do something, and you're desired _end result_. There are many valid answers to your question that won't help you achieve you goal. Explaining the context of the problem helps get better answers. – RobertL Nov 20 '15 at 19:18

2 Answers2

10

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

dhag
  • 15,440
  • 4
  • 54
  • 65
2

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"
done
chepner
  • 7,341
  • 1
  • 26
  • 27
  • I have similar script that does same as your 2nd script do but the 1st one is impressive . Thank you. – Raja G Nov 21 '15 at 10:14