bash 如何检查符号链接目标是否与特定路径匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19860345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a symlink target matches a specific path?
提问by Alex Guerrero
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. I've tried with readlink
:
我正在创建一个 bash 脚本来检查符号链接目标是否与特定路径匹配,因此,如果不匹配,脚本将删除符号链接。我试过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
回答by Radu R?deanu
You should use double quotes as follow when you compare strings (and yes, the output of readlink $HOME/.slate.js
is a string):
当你比较字符串时,你应该使用双引号如下(是的,输出readlink $HOME/.slate.js
是一个字符串):
[ "$(readlink $HOME/.slate.js)" = "$target_path" ]
回答by wrlee
In case $target_path
does not match the link text exactly, you can check that they are, in fact equivalent (regardless of name). But since a hardlink is preferable you might want to check that case, too (see below).
如果$target_path
与链接文本不完全匹配,您可以检查它们是否实际上等效(无论名称如何)。但由于硬链接更可取,您可能也想检查这种情况(见下文)。
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. If it is a hard link (which is preferable, when possible), then it is simpler:
但这一切都假设您$HOME/.slate.js
是一个符号链接。如果它是一个硬链接(如果可能的话,这是更可取的),那么它更简单:
… [ "$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.
您还应该检查该文件是否实际上是同一个文件(而不是硬链接),否则您将删除唯一的副本。