Should my script use cp or mv more reliable?

I have a bash script (Scientific Linux). The script should work with the file. Let's say "file.dat" (about 1 GB) After a while, the scripts are restarted and the following actions are performed:

if [ -f file.dat ]; then cp file.dat file.previous.dat fi 

to have a backup copy of the file. Then the process starts and overwrites the file "file.dat"

To be on the safest side (electricity turned off or something unexpected). What would be the best option: cp or mv? Thanks.

+6
source share
3 answers

I would use a combination:

 mv file.dat file.dat.previous cp file.dat.previous file.dat 

Thus, file.dat.previous will always be complete, since mv is atomic.

+5
source

The correct answer to the wrong question

If you need a fast, atomic move, then mv is what you need to do, since man 2 rename says:

If a new path already exists, it will be replaced by an atom (subject to several conditions, see ERRORS below), so it makes no sense that another process trying to access the new path does not detect it.

Perhaps, more importantly, mv is basically a directory entry operation, which is why it is very fast compared to copying a file in any normal circumstances.

The right answer to the right question

If you are concerned about power outages or unexpected system outages, follow these steps:

  • Attach an uninterruptible power supply. Indeed. Decide for a threat model.
  • Make sure you are using a battery-powered RAID controller.
  • Make critical recording synchronous.
  • Use a journaling file system that stores log data, not just metadata.

The mv command should be faster, but reliability in the face of catastrophic failures is a hardware or file system problem.

+4
source

This is probably not very useful here, but rsync is a tool for this kind of work. If the transfer is interrupted, it may reboot from where it needs to go.

+1
source

Source: https://habr.com/ru/post/919158/


All Articles