MacOS – Bash script – Delay cp command until after file write is complete

bashmacosscript

cp /Folder1/*.mov /Folder2/
cp /Folder1/*.mov /Folder3
rm /Folder1/*.mov

This runs every 60 seconds using Chron that copies any *.mov file from one folder to 2 other folders and then removes the file.

If the file takes longer than 60 seconds to write the script executes and copies anything in the folder and corrupts it. (Or if the script just happens to execute when a file is being written.)

How can I make a conditional statement to make the script wait until the file write is complete?

Best Answer

Lock File

Consider creating a lock to note the ongoing copy, see lock your script (against parallel run):

#!/bin/sh

# Path to a lock folder
LOCK_PATH="/tmp/copying.lock"

# Ensure the lock is removed should the copy fail
trap 'rmdir "/tmp/copying.lock"; exit' 1 6 15

if mkdir "$LOCK_PATH"; then
    # Lock file did not exist and was created

    # Perform commands
    cp /Folder1/*.mov /Folder2/
    cp /Folder1/*.mov /Folder3
    rm /Folder1/*.mov   

    # Remove the lock
    rmdir "$LOCK_PATH"
fi

The script above only copies if no folder exists at /tmp/copying.lock.

Copy and Move

Instead of copying directly to the final location, consider making the copy to a temporary location. Then move the files. A move is fast, tends to be atomic, and less likely to damage the files.

Alternatively, you could copy using a tool like rsync which includes flags to help protect against these problems.