帮助脚本交换目标和符号链接

帮助脚本交换目标和符号链接

我正在尝试创建一个脚本来交换当前目录中符号链接的位置和另一个(相对)目录中的目标文件。不幸的是,我不知道如何在非本地目录中建立链接,并且搜索有关“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

任何帮助将不胜感激。

答案1

假设您使用的是 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"

相关内容