如何检查文件在 Bash 中是否可执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42633413/
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 file is executable in Bash
提问by demoo
I am trying to build a condition that check if file has execute access bit set. I can't use grep and find.
我正在尝试建立一个条件来检查文件是否设置了执行访问位。我不能使用 grep 和 find。
I tried something with checking the "x" letter in the ls -l
command but this is wrong in many cases.
我尝试过检查ls -l
命令中的“x”字母,但在许多情况下这是错误的。
for val in `ls `
do
if [[ "`ls -l /$val`" -eq *w* ]]
then
rm /$val
fi
done
Please help or give some advices!
请帮忙或给一些建议!
回答by codeforester
There is no need to parse the output of ls
to see if a file is executable. Shell provides the built-in -x
check for that. Using -x
feature, your loop could be re-written as:
无需解析 的输出ls
以查看文件是否可执行。Shell 提供了内置的-x
检查。使用-x
功能,您的循环可以重写为:
for file in ""/*; do
[[ -x "$file" ]] && rm -- "$file"
done
See also:
也可以看看:
回答by iamauser
if [ -x "$file" ]; then
# do something
fi
You can get many more options of file testing using man
:
您可以使用以下命令获得更多文件测试选项man
:
~]# man test
....
-x FILE
FILE exists and execute (or search) permission is granted
Following should work:
以下应该工作:
~]# find -type f | while IFS='' read -r -d '' p;
do
if [ -x "$p" ]; then
echo "removing $p";
rm "$p";
fi;
done
find
command gets all the files (including .
) in the directory given by $1
. while
reads each of these output, if then
checks individual files for executable permission with-x
.
find
命令获取.
由$1
. while
读取这些输出中的每一个,if then
检查单个文件的可执行权限-x
。
EDIT
编辑
After some comments, here is a swifter example:
经过一些评论,这里有一个更快的例子:
find "" -type f -executable -exec rm -- {} \;