#!/bin/bash # Script to convert absolute symlinks to relative symlinks in a directory # Usage: ./relativize_symlinks.sh [directory] set -e # Function to calculate relative path from source to target calculate_relative_path() { local source="$1" local target="$2" # Convert to absolute paths to ensure consistency source=$(realpath -m "$source") target=$(realpath -m "$target") # Split paths into arrays IFS='/' read -ra source_parts <<< "${source#/}" IFS='/' read -ra target_parts <<< "${target#/}" # Find common prefix length local common_length=0 local min_length=$((${#source_parts[@]} < ${#target_parts[@]} ? ${#source_parts[@]} : ${#target_parts[@]})) for ((i=0; i $target" # Calculate the directory containing the symlink local symlink_dir symlink_dir=$(dirname "$symlink") # Convert absolute target to be relative to base directory local adjusted_target="${base_dir}${target}" # Calculate relative path from symlink location to target local relative_target relative_target=$(calculate_relative_path "$symlink_dir/dummy" "$adjusted_target") echo " Converting to: $symlink -> $relative_target" # Remove the old symlink and create the new relative one rm "$symlink" ln -s "$relative_target" "$symlink" echo " ✓ Converted successfully" fi done < <(find "$dir" -type l -print0) } # Main script main() { local target_dir="${1:-.}" # Validate directory exists if [[ ! -d "$target_dir" ]]; then echo "Error: Directory '$target_dir' does not exist" >&2 exit 1 fi # Get absolute path of target directory to use as base local abs_target_dir abs_target_dir=$(realpath "$target_dir") echo "Relativizing symlinks in: $abs_target_dir" echo "Using current directory as filesystem root" echo # Process the directory process_directory "$target_dir" "$abs_target_dir" echo echo "Symlink relativization complete!" } # Show usage if --help is passed if [[ "$1" == "--help" || "$1" == "-h" ]]; then echo "Usage: $0 [directory]" echo echo "Convert absolute symlinks to relative symlinks in the specified directory." echo "If no directory is specified, the current directory is used." echo echo "Example:" echo " $0 ./extracted_filesystem" echo echo "This will convert symlinks like:" echo " usr/lib/libz.so -> /lib/libz.so.1.2.11" echo "To:" echo " usr/lib/libz.so -> ../../lib/libz.so.1.2.11" exit 0 fi # Run main function main "$@"