Last active
February 15, 2021 17:38
-
-
Save haji-ali/7b84750daab3515dfd79c646a3d25877 to your computer and use it in GitHub Desktop.
Copy file, backing up the destination file if its different form the source.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#!/bin/bash | |
function copy-file { | |
SRC=$1 | |
DEST=$2 | |
# Make sure DEST is a file | |
if [ ! -f "$SRC" ]; then | |
echo "Source file does not exist" | |
return 1; | |
fi | |
# Make sure DEST is a file | |
if [ -d "$DEST" ]; then | |
$DEST="$DEST/$(basename $SRC)" | |
else | |
if [ ! -d "$(dirname "${DEST}")" ]; then | |
echo "Dest folder does not exist" | |
return 1; | |
fi | |
fi | |
if [ ! -f "$DEST" ]; then | |
cp $SRC $DEST | |
return 0; | |
fi | |
STATUS="$(cmp -s $SRC $DEST; echo $?)" # "$?" gives exit status for each comparison | |
if [[ $STATUS -eq 0 ]]; then # if status isn't equal to 0, then execute code | |
return 0; | |
fi | |
BACKUP_BASE="$DEST.bak" | |
BACKUP_FILE=$BACKUP_BASE | |
BACKUP_NUM=1 | |
until [ ! -f $BACKUP_FILE ] ; do | |
BACKUP_FILE=$BACKUP_BASE"."$BACKUP_NUM | |
((BACKUP_NUM=BACKUP_NUM+1)) | |
done | |
mv $DEST $BACKUP_FILE | |
cp $SRC $DEST | |
} | |
function copy-folder { | |
SRC=$1 | |
DEST=$2 | |
## https://unix.stackexchange.com/a/139381/332745 | |
while IFS= read -r -d '' -u 9 | |
do | |
echo "copy-file $REPLY $DEST$REPLY" | |
done 9< <( find $SRC -type f -exec printf '%s\0' {} + ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment