|
| 1 | +#!/bin/bash |
| 2 | +# |
| 3 | +# Copies a source folder to the destination folder via `rsync -a` and |
| 4 | +# fixes *absolute* links. Normally rsync only handles *relative* links |
| 5 | +# and preserves absolute links. This script searches for the copied |
| 6 | +# absolute links in the destination that are pointing to the original |
| 7 | +# source folder and updates them to reflect the new destination copy. |
| 8 | +# |
| 9 | +# Author: Stephen J. Carnam |
| 10 | +# Copyright (c) 2023 Virtuosoft / Stephen J. Carnam |
| 11 | +# License: MIT License |
| 12 | +# |
| 13 | + |
| 14 | +# Check for the correct number of arguments |
| 15 | +if [ "$#" -ne 2 ]; then |
| 16 | + echo "Usage: $0 <source folder> <destination folder>" |
| 17 | + exit 1 |
| 18 | +fi |
| 19 | + |
| 20 | +source_dir="$1" |
| 21 | +destination_dir="$2" |
| 22 | + |
| 23 | +# Ensure source directory ends with a trailing slash |
| 24 | +if [[ ! "$source_dir" == */ ]]; then |
| 25 | + source_dir="$source_dir/" |
| 26 | +fi |
| 27 | + |
| 28 | +# Ensure destination directory ends with a trailing slash |
| 29 | +if [[ ! "$destination_dir" == */ ]]; then |
| 30 | + destination_dir="$destination_dir/" |
| 31 | +fi |
| 32 | + |
| 33 | +# Perform the initial copy using rsync |
| 34 | +rsync -a "$source_dir" "$destination_dir" |
| 35 | + |
| 36 | +# Find absolute symbolic links within the destination directory |
| 37 | +absolute_links=() |
| 38 | +while IFS= read -r -d '' link; do |
| 39 | + absolute_links+=("$link") |
| 40 | +done < <(find "$destination_dir" -type l -lname '/*' -print0) |
| 41 | + |
| 42 | +# Loop through the absolute links and update them if needed |
| 43 | +for link in "${absolute_links[@]}"; do |
| 44 | + |
| 45 | + # Get the target of the symbolic link |
| 46 | + target=$(readlink -f "$link") |
| 47 | + |
| 48 | + # Check if the target contains the source directory path |
| 49 | + if [[ "$target" == *"$source_dir"* ]]; then |
| 50 | + |
| 51 | + # Replace the source directory path with the destination directory path |
| 52 | + new_target="${target//$source_dir/$destination_dir}" |
| 53 | + |
| 54 | + # Update the symbolic link to point to the new target |
| 55 | + rm "$link" |
| 56 | + ln -s "$new_target" "$link" |
| 57 | + echo "Updated: $link -> $new_target" |
| 58 | + fi |
| 59 | +done |
| 60 | + |
| 61 | +echo "Absolute symbolic links updated." |
0 commit comments