Bash - Overwrite file if content is different

By xngo on June 30, 2019

The function below will copy file to the destination directory. And, if the file already existed and have different content, then it will overwrite it. It uses cmp command to compare 2 files byte by byte.

function F_OVERWRITE_IF_DIFF()
{
    local FILE_PATH=$1
    local DEST_DIR=$2
 
    # Error handling
    if [ ! -f "${FILE_PATH}" ]; then 
        echo "Error: Input file: ${FILE_PATH}: no such file. Aborted!"
        exit 1
    fi;
    if [ ! -d "${DEST_DIR}" ]; then 
        echo "Error: Destination directory: ${DEST_DIR}: no such directory. Aborted!"
        exit 1
    fi;
 
 
    FILE_PATH=$(readlink -ev "${FILE_PATH}")
    DEST_DIR=$(readlink -ev "${DEST_DIR}")
 
    local FILENAME=$(basename "${FILE_PATH}")
    if [ -f "${DEST_DIR}/${FILENAME}" ]; then
 
        if ! cmp "${FILE_PATH}" "${DEST_DIR}/${FILENAME}" >/dev/null 2>&1; then
            yes | mv "${FILE_PATH}" "${DEST_DIR}"
        fi
 
    else
        mv "${FILE_PATH}" "${DEST_DIR}"
    fi
}
 
# Call the function.
F_OVERWRITE_IF_DIFF myfile.txt /to/destination/dir/

Reference

  • https://linux.die.net/man/1/cmp

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.