hardlink-or-copy 924 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env bash
  2. # Try to hardlink a file into a directory, fallback to copy on failure.
  3. #
  4. # Hardlink-or-copy the source file in the first argument into the
  5. # destination directory in the second argument, using the basename in
  6. # the third argument as basename for the destination file. If the third
  7. # argument is missing, use the basename of the source file as basename
  8. # for the destination file.
  9. #
  10. # In either case, remove the destination prior to doing the
  11. # hardlink-or-copy.
  12. #
  13. # Note that this is NOT an atomic operation.
  14. set -e
  15. main() {
  16. local src_file="${1}"
  17. local dst_dir="${2}"
  18. local dst_file="${3}"
  19. if [ -n "${dst_file}" ]; then
  20. dst_file="${dst_dir}/${dst_file}"
  21. else
  22. dst_file="${dst_dir}/${src_file##*/}"
  23. fi
  24. mkdir -p "${dst_dir}"
  25. rm -f "${dst_file}"
  26. ln -f "${src_file}" "${dst_file}" 2>/dev/null \
  27. || cp -f "${src_file}" "${dst_file}"
  28. }
  29. main "${@}"