Created
March 7, 2026 00:31
-
-
Save singularitti/a28985a50e7b6a44ebad18f4e24bfd6c to your computer and use it in GitHub Desktop.
Rewrite symbolic link targets whose paths start with a specified prefix #Shell #file-system
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This function scans a directory for symbolic links and replaces the | |
| # leading path prefix of each link target with a new prefix while keeping | |
| # the remainder of the path unchanged. | |
| # | |
| # Only links whose targets match the directory boundary pattern | |
| # OLD_PREFIX/* | |
| # are modified. This prevents accidental matches such as | |
| # /path/foo2 | |
| # when replacing | |
| # /path/foo | |
| # | |
| # Trailing slashes in prefixes are automatically normalized. | |
| # | |
| # Parameters | |
| # ---------- | |
| # BASE_DIR | |
| # Directory containing symlinks to examine. | |
| # | |
| # OLD_PREFIX | |
| # Existing path prefix in the symlink targets. | |
| # | |
| # NEW_PREFIX | |
| # Replacement prefix for the targets. | |
| # | |
| # DRY_RUN (optional) | |
| # 1 → preview changes only (default) | |
| # 0 → apply modifications | |
| # | |
| # Example | |
| # ------- | |
| # Mn10Si2Bi1_615 -> /scratch/04996/tg842951/MnBiX_PBE2/Mn10Si2Bi1_615 | |
| # | |
| # Running: | |
| # | |
| # relink_prefix . \ | |
| # /scratch/04996/tg842951/MnBiX_PBE2 \ | |
| # /work2/04996/tg842951/stampede3/run/MnBiX_PBE2 | |
| # | |
| # will produce: | |
| # | |
| # Mn10Si2Bi1_615 -> /work2/04996/tg842951/stampede3/run/MnBiX_PBE2/Mn10Si2Bi1_615 | |
| # | |
| # Notes | |
| # ----- | |
| # - Only symbolic links are processed. | |
| # - Targets not matching OLD_PREFIX are skipped. | |
| # - Absolute paths are recommended. | |
| # | |
| relink_prefix() { | |
| local base_dir="${1:-.}" | |
| local old_prefix="${2%/}" | |
| local new_prefix="${3%/}" | |
| local dry_run="${4:-1}" | |
| if [ $# -lt 3 ]; then | |
| echo "Usage: relink_prefix BASE_DIR OLD_PREFIX NEW_PREFIX [DRY_RUN]" | |
| return 1 | |
| fi | |
| find "$base_dir" -type l | while IFS= read -r link; do | |
| local target suffix new_target | |
| target=$(readlink "$link") || continue | |
| case "$target" in | |
| "$old_prefix"/*) | |
| suffix="${target#"$old_prefix"}" | |
| new_target="${new_prefix}${suffix}" | |
| echo "$link" | |
| echo " OLD: $target" | |
| echo " NEW: $new_target" | |
| if [ "$dry_run" != "1" ]; then | |
| ln -sfn "$new_target" "$link" | |
| fi | |
| ;; | |
| esac | |
| done | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment