Skip to content

Instantly share code, notes, and snippets.

@Sap333
Last active November 5, 2015 22:48
Show Gist options
  • Save Sap333/fac1caa2eb77258ce8b2 to your computer and use it in GitHub Desktop.
Save Sap333/fac1caa2eb77258ce8b2 to your computer and use it in GitHub Desktop.
Copy a directory tree using hardlinks (converting soft links to hard links).
#!/bin/bash
function printUsage {
echo "Usage:
$(basename "${BASH_SOURCE[0]}") <SRC_DIR> <DST_DIR>
Makes a recursive copy of <SRC_DIR> to <DST_DIR> using harlinks and avoiding softlinks.
If <DST_DIR> exists then creates there a subdirectory with name of <SRC_DIR>. Otherwise,
creates <DST_DIR> and uses it as a destination directory." >&2
exit $0
}
[[ "$1" == '-h' || "$1" == '--help' ]] && printUsage 0
[ $# -ne 2 ] && { echo "Error: Wrong parameter count." >&2 ; printUsage 1 ; }
function _cp-hl {
[ $# -ne 2 ] && { echo "Error: There must be two parameters (SOURCE and DEST)." >&2 ; return 1 ; }
[ -d "$1" ] || { echo "Error: The source directory doesn't exist." >&2 ; exit 2 ; }
local SRCLEN=${#1}
if [ -d "$2" ]; then local DST="$(readlink -m "$2/$(basename "$1")")" || return $?
else local DST="$(readlink -m "$2")" || retun $?; fi
find -L "$1" -exec bash -c '[ -d "$1" ] && { mkdir "$2/${1:$3}" ; exit ;} ; \
ln -fL "$1" "$2/${1:$3}" ; exit ;' '' {} "$DST" $SRCLEN \; \
&& find -L "$1" -type d -exec bash -c 'touch -m -r "$1" "$2/${1:$3}"' '' {} "$DST" $SRCLEN \;
}
_cp-hl "$1" $2" ; exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment