Skip to content

Instantly share code, notes, and snippets.

@haji-ali
Last active February 15, 2021 17:38
Show Gist options
  • Save haji-ali/7b84750daab3515dfd79c646a3d25877 to your computer and use it in GitHub Desktop.
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.
#!/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