将绝对转换为相对符号链接

时间:2018-10-31 09:41:01

标签: bash sh symlink

我同步目录“ Promotion”,其中包含具有不同目录结构的两台计算机之间的绝对符号链接。因此,绝对符号链接在两台计算机上均不起作用。为了使它们起作用,我想将它们转换为相对链接。 目录结构为

Machine 1: /home/user/Privat/Uni Kram/Promotion/
Machine 2: /homes/user/Promotion/

以下是两个示例符号链接:

 4821      1 lrwxrwxrwx   1 manu  users         105 Nov 17  2014 ./Planung\ nach\ Priorit\303\244ten.ods -> /home/manu/Dokumente/Privat/Uni\ Kram/Promotion/Pl\303\244ne\ und\ Ideen/Pl\303\244ne/Planung\ nach\ Priorit\303\244ten.ods  
37675      1 lrwxrwxrwx   1 manu  users         102 Aug  3  2015 ./Kurs/Lab\ Course\ Somewhere -> /home/manu/Dokumente/Privat/Uni\ Kram/Promotion/Workshops\ &\ Fortbildungen/Kurs\ Lab\ Course\ Somewhere

我的非工作尝试是(基于示例this):

find * -type l -print | while read l; do 
ln -srf $(cut -c 24- < $(readlink $l)) $l;
done

4 个答案:

答案 0 :(得分:0)

以下可能有效。

请注意

  • 如果不希望通过mv ..更改rm,请备份链接
  • 查找参数必须是绝对的,否则函数将拒绝链接

示例

find /absolute/path/to/root -type l -exec bash -c $'
    abs_to_relative() {
        l=$1
        t=$(readlink "$1")
        [[ $l = /* ]] && [[ $t = /* ]] && [[ $l != "$t" ]] || return
        set -f
        IFS=/
        link=($l)
        target=($t)
        IFS=$\' \\t\\n\'
        set +f
        i=0 f=\'\' res=\'\'
        while [[ ${link[i]} = "${target[i]}" ]]; do ((i+=1)); done
        link=("${link[@]:i}")
        target=("${target[@]:i}")
        for ((i=${#link[@]};i>1;i-=1)); do res+=../; done
        res=${res:-./}
        for f in "${target[@]}"; do res+=$f/; done
        res=${res%/}
        # rm "$1"
        mv "$1" "$1.bak"
        ln -s "$res" "$1"
    }
    for link; do abs_to_relative "$link"; done
' links {} +

已完成的测试

mkdir -p /tmp/testlink/home{,s}/user/abc
touch /tmp/testlink/home/user/{file0,abc/file1}.txt
ln -s /tmp/testlink/home/user/abc/file1.txt /tmp/testlink/home/user/link1.txt
ln -s /tmp/testlink/home/user/file0.txt /tmp/testlink/home/user/abc/link0.txt
ln -s /tmp/testlink/home/user/    /tmp/testlink/home/user/abc/linkdir
# ... command
rm -rf /tmp/testlink

答案 1 :(得分:0)

谢谢大家的帮助。经过一番尝试,我根据您的注释和代码提出了一个解决方案。 这是解决我的问题的方法:

#!/bin/bash
# changes all symbolic links to relative ones recursive from the current directory
find * -type l -print | while read l; do 
cp -a "$l" "$l".bak
linkname="$l"
linktarget=$(readlink "$l")
echo "orig linktarget"
echo $linktarget
temp_var="${linktarget#/home/user/Privat/Uni Kram/Promotion/}"
echo "changed linktarget"
echo $temp_var;
ln -sfr "$temp_var" "$l"
echo "new linktarget in symlink"
readlink "$l";
done

答案 2 :(得分:0)

这是使用python3进行此操作的解决方案。

from pathlib import Path

d = Path("/home/user/Privat/Uni Kram/Promotion/")
all_symlinks = [p for p in d.rglob("*") if p.is_symlink()]

def make_symlink_relative(p):
    assert p.is_symlink()
    relative_target = p.resolve(strict=True).relative_to(p.absolute().parent)
    p.unlink() 
    # this while-loop protects against race conditions
    while True:
        try:
            p.symlink_to(relative_target)
            break
        except FileExistsError:
            pass

for symlink in all_symlinks:
    make_symlink_relative(symlink)

答案 3 :(得分:0)

这是在两个方向上转换的一对函数。现在,我在~/bin中有了这些内容,可以更广泛地使用它们。链接不必位于当前目录中。只需用作:

lnsrelative <link> <link> <link> ...
lnsabsolute <link> <link> <link> ...
#!/bin/bash
# changes absolute symbolic links to relative
# will work for links & filenames with spaces

for l in "$@"; do
    [[ ! -L "$l" ]] && echo "Not a link: $l" && exit 1
done
    
for l in "$@"; do
    # Use -b here to get a backup.  Unnecessary because reversible.
    ln -sfr "$(readlink "$l")" "$l"
done

#!/bin/bash
# changes relative symbolic links to absolute
# will work for links & filenames with spaces

for l in "$@"; do
    [[ ! -L "$l" ]] && echo "Not a link: $l" && exit 1
done
    
for l in "$@"; do
    # Use -b here to get a backup.  Unnecessary because reversible.
    ln -sf "$(realpath "$(readlink "$l")")" "$l"
done

为完整起见,这会将符号链接更改为硬链接,用作:

lnstohard <link> <link> <link>
#!/bin/bash
# changes symbolic links to hard links
# This will work for filenames with spaces, 
# but only for regular files in the same filesystem as the link.
# Thorough discussion of correct way to confirm devices are the same:
# https://unix.stackexchange.com/questions/120810/check-if-2-directories-are-hosted-on-the-same-partition-on-linux

for l in "$@"; do
    [[ ! -L "$l" ]] && echo "Not a symbolic link: $l" && exit 1
    
    rl="$(readlink "$l")"
    rld="$(dirname "$l")"
    [[ ! -e "$rl" || -d "$rl" || "$(df --output=target "$rld")" != "$(df --output=target "$rl")" ]] && \
        echo "Target \"$rl\" must exist on same filesystem as link \"$l\", and may not be a directory" && \
        exit 1
done

for l in "$@"; do
    # Using -b here to get a backup, because it's not easy to revers a soft->hard link conversion
    ln -fb "$(readlink "$l")" "$l"
done