When I move a file using the mv command, is this file first read, fully cached into a memory and then saved as another file? Or is it the same as writing

while read line; do
    echo "$line" >> output_file
done < input_file

Similarly with cp. When copying one file to another, is the file first fully cached into memory and then copied?

  • 3
    If you do an actual copy, the process will allocate a buffer in memory, read a chunk, then write a chunk. The whole file will pass through that buffer but is unlikely to all be in memory at the same time. – Basic Jun 14 '16 at 19:31
  • 3
    No matter what it won't be the same as using a shell loop to process text, which you should never do. See Why is using a shell loop to process text considered bad practice? – Wildcard Jun 14 '16 at 21:18
  • My biggest concern about using mv is when I have a limited size of a memory. Is it (not) likely to run out of memory when using mv since it is managed "inside the command"? – Superian007 Jun 15 '16 at 12:44

Often a mv is closer to a rename than a copy. In a classic unix type file system, the inodes that contain the file data won't be replicated if the source and the destination are on the same mount point. Instead a new filename is created that points to the same inodes, and the old filename is unlinked.

If the mv is to another mount point, then it will be an actual copy. What fraction of it is in RAM at a time is an OS detail whose transparency to the user is not defined.

Just to give an example, if the data was considered actually copied to a new place, the file might be, to the user, conceptually 'written' to the disk. But it could, at the OS level, actually be residing in a buffer that hasn't been flushed to the hardware yet.

  • 1
    …and it does. Small files don't trigger a disk flush right away on most distrib default settings. – spectras Jun 14 '16 at 16: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.