env.sh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/bin/bash
  2. # Check if the correct number of arguments are provided
  3. if [ "$#" -ne 2 ]; then
  4. echo "Usage: $0 <src> <dest>"
  5. exit 1
  6. fi
  7. src="$1"
  8. dest="$2"
  9. # Function to copy and link files
  10. copy_and_link() {
  11. local src_file="$1"
  12. local dest_file="$2"
  13. if [ -L "$src_file" ]; then
  14. # If src_file is a symbolic link, copy it without changing permissions
  15. cp -P "$src_file" "$dest_file"
  16. elif [ -b "$src_file" ] || [ -c "$src_file" ]; then
  17. # If src_file is a device file, copy it and change permissions
  18. cp "$src_file" "$dest_file"
  19. chmod 444 "$dest_file"
  20. else
  21. # Otherwise, create a hard link and change the permissions to read-only
  22. ln -f "$src_file" "$dest_file" 2>/dev/null || { cp "$src_file" "$dest_file" && chmod 444 "$dest_file"; }
  23. fi
  24. }
  25. # Check if src is a file or directory
  26. if [ -f "$src" ]; then
  27. # src is a file, create hard link directly in dest
  28. mkdir -p "$(dirname "$dest/$src")"
  29. copy_and_link "$src" "$dest/$src"
  30. elif [ -d "$src" ]; then
  31. # src is a directory, process as before
  32. mkdir -p "$dest/$src"
  33. # Find all files in the source directory
  34. find "$src" -type f,l | while read -r file; do
  35. # Get the relative path of the file
  36. rel_path="${file#$src/}"
  37. # Get the directory of the relative path
  38. rel_dir=$(dirname "$rel_path")
  39. # Create the same directory structure in the destination
  40. mkdir -p "$dest/$src/$rel_dir"
  41. # Copy and link the file
  42. copy_and_link "$file" "$dest/$src/$rel_path"
  43. done
  44. else
  45. echo "Error: $src is neither a file nor a directory"
  46. exit 1
  47. fi