orglinks.sh 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/bin/bash
  2. #
  3. # ChatGPT Promt:
  4. #
  5. # write me a bash script that finds all the .org files under $HOME and
  6. # hard links them to ~/orgfiles/, changing the "/" in paths to "__"
  7. # This is bash, be safe
  8. set -u
  9. set -e
  10. # use my info,warn,error aliases
  11. source ~/lib/bash/bashutils.sh
  12. # Define source and destination directories
  13. source_dir="$HOME"
  14. destination_dir="$HOME/orgfiles"
  15. # Max hard links to make. If I have more than 10k org files, there are problems.
  16. MAXFILES=10000
  17. # Create the destination directory if it doesn't exist
  18. mkdir -p "$destination_dir"
  19. # Find all .org files under $HOME and loop through them
  20. find "$source_dir" -type f -name "*.org" | grep -v "$destination_dir" | head -$MAXFILES | while read -r original_file; do
  21. # Get the relative path by removing the source directory part
  22. relative_path=${original_file#"$source_dir"/}
  23. # Replace "/" in paths with "__"
  24. modified_relative_path1="${relative_path//\//__}"
  25. # Replace " " in paths with "_"
  26. modified_relative_path="${modified_relative_path1// /_}"
  27. # Construct the destination path
  28. local_link_to_original="$destination_dir/$modified_relative_path"
  29. # if local link and original file both exist and have different inode numbers,
  30. # remove the local link
  31. if [ -e "$original_file" ] && [ -e "$local_link_to_original" ] && [ "$(stat -c%i -- "$original_file")" != "$(stat -c%i -- "$local_link_to_original")" ]; then
  32. warn "inode number of original file ${original_file} and linked file have changed. Removing linked file."
  33. \rm -f "$local_link_to_original"
  34. fi
  35. # if the target file exists, continue
  36. if [ -f "$local_link_to_original" ] ; then
  37. continue
  38. fi
  39. # Attempt to create a hard link to the destination
  40. if ln "$original_file" "$local_link_to_original" 2>/dev/null; then
  41. info "Linked file: $original_file -> $local_link_to_original"
  42. else
  43. warn "Failed to create a hard link for $original_file to $local_link_to_original"
  44. fi
  45. done