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