如何检测 Bash 中的符号链接是否已损坏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8049132/
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 can I detect whether a symlink is broken in Bash?
提问by zoltanctoth
I run find
and iterate through the results with [ \( -L $F \) ]
to collect certain symbolic links.
我运行find
并迭代结果[ \( -L $F \) ]
以收集某些符号链接。
I am wondering if there is an easy way to determine if the link is broken (points to a non-existent file) in this scenario.
我想知道在这种情况下是否有一种简单的方法可以确定链接是否已损坏(指向不存在的文件)。
Here is my code:
这是我的代码:
FILES=`find /target/ | grep -v '\.disabled$' | sort`
for F in $FILES; do
if [ -L $F ]; then
DO THINGS
fi
done
回答by Roger
# test if symlink is broken (by seeing if it links to an existing file)
if [ ! -e "$F" ] ; then
# code if the symlink is broken
fi
回答by Shawn Chin
This should print out links that are broken:
这应该打印出损坏的链接:
find /target/dir -type l ! -exec test -e {} \; -print
You can also chain in operations to find
command, e.g. deleting the broken link:
您还可以将操作find
链接到命令,例如删除断开的链接:
find /target/dir -type l ! -exec test -e {} \; -exec rm {} \;
回答by Aquarius Power
this will work if the symlink was pointing to a file or a directory, but now is broken
如果符号链接指向文件或目录,这将起作用,但现在已损坏
if [[ -L "$strFile" ]] && [[ ! -a "$strFile" ]];then
echo "'$strFile' is a broken symlink";
fi
回答by Andrew Schulman
readlink -q
will fail silently if the link is bad:
readlink -q
如果链接不好,将静默失败:
for F in $FILES; do
if [ -L $F ]; then
if readlink -q $F >/dev/null ; then
DO THINGS
else
echo "$F: bad link" >/dev/stderr
fi
fi
done
回答by ACyclic
This finds all files of type "link", which also resolves to a type "link". ie. a broken symlink
这将找到所有“链接”类型的文件,该文件也解析为“链接”类型。IE。损坏的符号链接
find /target -type l -xtype l
回答by William Pursell
If you don't mind traversing non-broken dir symlinks, to find all orphaned links:
如果您不介意遍历未损坏的目录符号链接,请查找所有孤立链接:
$ find -L /target -type l | while read -r file; do echo $file is orphaned; done
To find all files that are not orphaned links:
要查找所有不是孤立链接的文件:
$ find -L /target ! -type l
回答by Rew Brian
What's wrong with:
有什么问题:
file $f | grep 'broken symbolic link'
file $f | grep 'broken symbolic link'