Bash

幫助腳本交換目標和符號連結

  • January 15, 2021

我正在嘗試創建一個腳本來交換目前目錄中符號連結的位置和另一個(相對)目錄中的目標文件。不幸的是,我不知道如何在非本地目錄中創建連結並蒐索“ln -s”上的資訊僅檢索簡單的案例使用。我意識到我可以“cd”到腳本中的另一個目錄,但我認為必須有一種更“優雅”的方式。

這就是我所擁有的

#!/bin/bash
#
# Script to help organize repositories.
# Finds local links and swaps them with their target.
#
# Expects 1 arguments

if [ "$#" -ne 1 ];
then
   echo "Error in $0:  Need 1 arguments: <SYMBOLICLINK>";
   exit 1;
fi



LINK="$1";
LINKBASE="$(basename "$LINK")";
LINKDIR="$(dirname "$LINK")";
LINKBASEBKUP="$LINK-bkup";

TARGET="$(readlink "$LINK")";
TARGETBASE="$(basename "$TARGET")";
TARGETDIR="$(dirname "$TARGET")";

echo "Link:   $LINK";
echo "Target: $TARGET";

#Test for broken link
# test if symlink is broken (by seeing if it links to an existing file)
if [ -h "$LINK" -a ! -e "$LINK"  ] ; then
   echo "Symlink $LINK is broken.";
   echo "Exiting\n";
   exit 1;
fi


mv -f "$TARGET" "/tmp/.";
#   printf "$TARGET copied to /tmp/\n" || exit 1;
mv -f "$LINK" "/tmp/$LINKBASEBKUP";# &&
#   printf "$LINKBASE copied to /tmp/$LINKBASEBKUP\n"; # ||

#   { printf "Exiting"; exit 1; }
# and alternative way to check errors
# [ $? -neq 0 ] && printf "Copy $LINK to $REFDIRNEW failed\nExiting"

mv "/tmp/$TARGETBASE" "$LINK";  #what was a link is now a file (target)
ln -s "$LINK" "$TARGET"; #link is target and target is link

if [ $? -eq 0 ];
then
   echo "Success!";
   exit 0
else
   echo "Couldn't make link to new target. Restoring link and target and exiting";
   mv "/tmp/$LINKBASEBKUP" "$LINK";
   mv "/tmp/$TARGETBASE" "$TARGET";
   exit 1;
fi

任何幫助將不勝感激。

假設您使用的是 GNU 工具,您可以確定連結和目標的絕對路徑,並使用ln -r或使用realpath--relative-to選項來創建相對連結目標。

這是一個沒有完整性檢查或清理連結備份的最小範例:

#!/bin/bash

link=$(realpath -s "$1")  # absolute path to link
target=$(realpath "$1")   # absolute path to target

mv -vf "$link"{,.bak}     # create link backup
mv -vf "$target" "$link"  # move target

# a) use ln -r
ln -vsr "$link" "$target"

# b) or determine the relative path
#target_dir=$(dirname "$target")
#relpath=$(realpath --relative-to="$target_dir" "$link")
#ln -vs "$relpath" "$target"

引用自:https://unix.stackexchange.com/questions/629224