Copying files ... with style

The venerable cp command is well-known to any Unixer. Whether you want to copy one file or a whole tree recursively, cp is always available and always ready to help.

However, as with most things in life there is more than one way to cp the cat. In this article, I’m going to explore some alternatives to cp that you can use … if you dare.

Copying single files

Copying files to other files, or into a new directory, is fairly simple. All you need to do is ensure that the bytes in file A are replicated in file B, creating B if necessary. Copying multiple files from one directory to another is a little more complicated, but only a little.

File → File

In each of these examples, FROM is the source file and TO is the destination file:

  • dd if=FROM of=TO — you can even add status=progress to see how much is copied at a time!
  • cat TO, cat FROM >TO — cat isn’t just for text files.
  • curl -o TO file://localhost/FROM — curl isn’t just for http(s), ftp(s), dict, gopher(s), imap(s), ldap(s), mqtt, pop3(s), rtsp, scp, sftp, smb(s), smtp(s), telnet, tftp, or ws(s); it can do files too!

You can also use the shell itself … if you’re copying a text file. There might be a way to copy binary files this way, but I don’t know it.

:>TO
while read -r line
do prinf '%s\n' "$line" >> TO
done < FROM

Files → Directory

To copy multiple files to a given directory, you can use any of the above methods in a for loop. The only real complication is getting the filenames right. Here is a template using the dd method above:

mkdir TO_DIR
for F in FROM...
do dd if="$F" of="$TO_DIR/${F##*/}"
done

Recursively copying directories

Honestly, I mostly use cp -a to recursively copy directories, and that’s only when I forget about rsync -zaP. This is an area where a purpose-built tool is what you want to reach for; recursive copying is pretty complicated.

However, if you don’t have cp or rsync, but do for some reason have tar, this’ll work (it works for moving multiple single files to a new directory, too; just specify multiple FROMs):

tar cf - FROM_DIR | (cd $(mkdir -d); tar xf -; mv * TO_DIR/)

How else can you copy a file?

I’m going to keep updating this page as I come up with new ways to copy files without using cp. If you have found one I’ve missed, please email me and let me know! I’ll copy it to this page posthaste.

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论