I want to copy-backup several files in different folder at once before updating ntpd.

Example (one file only): sudo cp /usr/sbin/ntpd /usr/sbin/ntpd.old



Desired result:


Does a smart one-liner exist to accomplish this task?


Use xargs:

cat filelist | xargs -I {} cp {} {}.old
  • and how may i do this without an explicit filelist-file.
    – klanomath
    Dec 24 '14 at 12:27
  • xargs takes lines from standard input to build and run commands. You can run xargs -I {} cp {} {}.old, input filenames (on separate lines) by hand (or via paste) and press Ctrl+D (marks end of input).
    – andrybak
    Dec 24 '14 at 12:30
  • There's a useless use of cat, and the preferred way to pipe to xargs (if even needed) is to use find … -print0 | xargs -0.
    – slhck
    Dec 24 '14 at 12:33

Using a shell loop

Something like a simple loop, iterating over two directories and then matching files:

for dir in /usr/bin /usr/sbin; do
  for file in "$dir/"*ntp*; do 
    sudo cp "$dir/$file" "$dir/$file.old"

This will copy all files matching the *ntp* pattern in both directories to the same file name, with .old appended.

Make sure to quote the variables correctly as a safeguard against files with whitespace in their name. The pattern *ntp* must not be quoted so that it can be expanded.

Using find

You could use find and -exec too:

find /usr/bin /usr/sbin -type f -iname '*ntp*' -exec sudo cp {} {}.old \;

The above would be safer since it only runs on files – but you're not expecting to have directories called ntp, so that's fine, I suppose.

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.