Skip to content

Instantly share code, notes, and snippets.

@adamesque
Created December 22, 2012 00:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamesque/4356738 to your computer and use it in GitHub Desktop.
Save adamesque/4356738 to your computer and use it in GitHub Desktop.
Replace a symlink with a copy of its target.
#!/usr/bin/env bash
set -e
symlink=$1
main() {
enforce_usage
if [[ -h $symlink ]]; then
remove_and_copy
fi
}
remove_and_copy() {
# c.f. http://superuser.com/questions/303559/replace-symbolic-links-with-files
dir=$(dirname "$symlink")
reltarget=$(readlink "$symlink")
if [[ $reltarget == /* ]]; then
abstarget=$reltarget
else
abstarget=$dir/$reltarget
fi
rm -fv "$symlink"
cp -afv "$abstarget" "$symlink" || {
# on failure, restore the symsymlink
rm -rfv "$symlink"
ln -sfv "$reltarget" "$symlink"
}
}
enforce_usage() {
if [[ -z $symlink ]] || [[ ! -h $symlink ]]; then
usage
fi
}
usage() {
echo -e "Replaces a symlink with a copy of its target."
echo -e "usage: `basename $0` [<symlink>]"
# echo -e " `basename $0` [<former_symlink>]"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment