简体   繁体   English

如何检查符号链接目标是否与特定路径匹配?

[英]How to check if a symlink target matches a specific path?

I'm creating a bash script to check if a symlink target matches a specific path so, in case it doesn't match, script removes the symlink. 我正在创建一个bash脚本来检查符号链接目标是否与特定路径匹配,因此,如果它不匹配,脚本将删除符号链接。 I've tried with readlink : 我尝试过readlink

#!/bin/env bash

target_path=$HOME/Code/slate/.slate.js

if [ `readlink $HOME/.slate.js` == "$target_path" ]; then
    rm -rf "$HOME/.slate.js"
fi

but it doesn't work: 但它不起作用:

%source test
test:5: = not found

比较字符串时应该使用双引号(是的, readlink $HOME/.slate.js的输出是一个字符串):

[ "$(readlink $HOME/.slate.js)" = "$target_path" ]

In case $target_path does not match the link text exactly, you can check that they are, in fact equivalent (regardless of name). 如果$target_path与链接文本不完全匹配,您可以检查它们实际上是等价的(无论名称如何)。 But since a hardlink is preferable you might want to check that case, too (see below). 但是,由于硬链接更可取,您可能也想检查这种情况(见下文)。

A more generic solution is: 更通用的解决方案是:

[ "$(readlink $HOME/.slate.js)" -ef "$target_path" ]

Or, as in your example: 或者,如您的示例所示:

target_path=$HOME/Code/slate/.slate.js

if [ "`readlink $HOME/.slate.js`" -ef "$target_path" ]; then
    rm -rf "$HOME/.slate.js"
fi

But that all assumes that your $HOME/.slate.js is a symbolic link. 但这一切都假设你的$HOME/.slate.js是一个符号链接。 If it is a hard link (which is preferable, when possible), then it is simpler: 如果它是一个硬链接(如果可能的话,这是更可取的),那么它更简单:

 … [ "$HOME/.slate.js" -ef "$target_path" ] …

Maybe something like (check whether it is a symlink, if so, then check that link matches target; otherwise check whether the files same—either a hard link or actually the same file): 也许类似(检查它是否是符号链接,如果是这样,然后检查该链接是否与目标匹配;否则检查文件是否相同 - 硬链接或实际上是同一文件):

 … [ \( -L "$HOME/.slate.js" -a "`readlink $HOME/.slate.js`" -ef "$target_path" \) \
     -o \( "$HOME/.slate.js" -ef "$target_path" \) ] …

You should also check whether the file is, in fact, the same file (and not a hard link), otherwise you will delete the one and only copy. 您还应该检查文件实际上是否是同一个文件(而不是硬链接),否则您将删除该文件并且仅复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM