如何检查文件在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:51:44  来源:igfitidea点击:

How to check if a file is executable in Bash

bashls

提问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 -lcommand 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 lsto see if a file is executable. Shell provides the built-in -xcheck for that. Using -xfeature, 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

findcommand gets all the files (including .) in the directory given by $1. whilereads each of these output, if thenchecks 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 -- {} \;