How to avoid race condition when mounting, copying files into, and umounting images

This script creates ten image files and copy over file(s) to them.

#!/bin/bash
# script to create multiple floppy images for installing hwp30
#+on virtualbox.

# umount image in case mounted
sudo umount /media/floppy

# create ten blank 2.88mb images.
#+then mount each image and copy over file(s).
for n in {1..10}; do
    mkfs.msdos -C "hwp30-${n}.img" 2880
    sudo mount -o loop "hwp30-${n}.img" /media/floppy
    sudo cp -v "../DISK${n}" /media/floppy

    # if first disk then copy over INSTALL.EXE
    if [[ $n -eq 1 ]]; then
        sudo cp -v ../INSTALL* /media/floppy
    fi
    
    sudo umount /media/floppy
done

# done?
if [[ $? -eq 0 ]]; then
    echo "done!"
fi

When I run this script, mounting, copying of files and umounting are out of sync; they are not done in the correct order. Umounting says 'device is busy' a few times.

After the script finishes I need to do umount command several times to umount them all(even though it is the same mount point?).

I think this is called a race condition. How to fix?


The problem might be that, even though the copy has finished, ther is still IO going on from cache to the mounted image.

Add sync; sync just before the line with sudo umount /media/floppy.. this will request a flush of unwritten data - and wait for it to happen.