如何在 Bash 中检查文件是否可执行
How to check if a file is executable in Bash
我正在尝试建立一个条件来检查文件是否设置了执行访问位。我不能使用 grep 和查找。
我尝试检查 ls -l
命令中的 "x" 字母,但在很多情况下这是错误的。
for val in `ls `
do
if [[ "`ls -l /$val`" -eq *w* ]]
then
rm /$val
fi
done
请大家帮忙或指点一下!
if [ -x "$file" ]; then
# do something
fi
您可以使用 man
获得更多文件测试选项:
~]# man test
....
-x FILE
FILE exists and execute (or search) permission is granted
以下应该有效:
~]# find -type f | while IFS='' read -r -d '' p;
do
if [ -x "$p" ]; then
echo "removing $p";
rm "$p";
fi;
done
find
命令获取</code>给定目录下的所有文件(包括<code>.
)。 while
读取每个输出,if then
使用 -x
检查单个文件的可执行权限。
编辑
经过一些评论,这里有一个更快捷的例子:
find "" -type f -executable -exec rm -- {} \;
无需解析 ls
的输出即可查看文件是否可执行。 Shell 提供内置的 -x
检查。使用 -x
功能,您的循环可以重写为:
for file in ""/*; do
[[ -x "$file" ]] && rm -- "$file"
done
另请参阅:
- How do I tell if a regular file does not exist in Bash?
As Charles suggested - Why you shouldn't parse the output of ls(1)
BashFAQ/087 - How can I get a file's permissions (or other metadata) without parsing ls -l output
我正在尝试建立一个条件来检查文件是否设置了执行访问位。我不能使用 grep 和查找。
我尝试检查 ls -l
命令中的 "x" 字母,但在很多情况下这是错误的。
for val in `ls `
do
if [[ "`ls -l /$val`" -eq *w* ]]
then
rm /$val
fi
done
请大家帮忙或指点一下!
if [ -x "$file" ]; then
# do something
fi
您可以使用 man
获得更多文件测试选项:
~]# man test
....
-x FILE
FILE exists and execute (or search) permission is granted
以下应该有效:
~]# find -type f | while IFS='' read -r -d '' p;
do
if [ -x "$p" ]; then
echo "removing $p";
rm "$p";
fi;
done
find
命令获取</code>给定目录下的所有文件(包括<code>.
)。 while
读取每个输出,if then
使用 -x
检查单个文件的可执行权限。
编辑
经过一些评论,这里有一个更快捷的例子:
find "" -type f -executable -exec rm -- {} \;
无需解析 ls
的输出即可查看文件是否可执行。 Shell 提供内置的 -x
检查。使用 -x
功能,您的循环可以重写为:
for file in ""/*; do
[[ -x "$file" ]] && rm -- "$file"
done
另请参阅:
- How do I tell if a regular file does not exist in Bash?
As Charles suggested - Why you shouldn't parse the output of ls(1)
BashFAQ/087 - How can I get a file's permissions (or other metadata) without parsing ls -l output