如何在当前目录中查找可执行文件并找出它们的扩展名?

3

我需要从/bin目录中找出所有可执行文件。如何使用

find . -executable

如何检查文件是否为脚本(例如sh,pl,bash)?


在你的查找命令中添加“-type f”以筛选掉子目录。 - glenn jackman
在 /bin 目录下是否有任何非可执行文件? - uzsolt
4个回答

4
#!/bin/bash                                                                                                                                                    

for file in `find /bin` ; do                                                                                                                                   
    if [ -x $file ] ; then                                                                                                                                     
        file $file                                                                                                                                             
    fi                                                                                                                                                         
done

更好的做法

find /bin -type f -perm +111 -print0 | xargs -0 file

1

查找所有的 shell 脚本

find . -type f -executable | xargs file -i | grep x-shellscript | cut -d":" -f1

查找所有可执行文件

find . -type f -executable | xargs file -i | grep x-exec | cut -d":" -f1

查找所有共享库

find . -type f -executable | xargs file -i | grep x-sharedlib | cut -d":" -f1

1

find /bin/ -executable 返回 /bin/ 目录下所有可执行文件。

使用 -name 标志进行扩展名过滤。例如,find /bin/ -executable -name "*.sh" 返回 sh 脚本。

更新:

如果文件不是二进制文件且没有扩展名,则可以从 shabang 中推断出其类型。

例如,find ~/bin/ -executable | xargs grep --files-with-matches '#!/bin/bash' 返回包含 #!/bin/bash 的文件,这些文件来自于 ~/bin/ 目录。


谢谢,但如果文件没有扩展名,如何确定脚本类型? - DmitryB
2
在执行“#!/bin/bash”的grep命令时,有可能会出现误报的风险,同时还有可能错过使用/bin/sh的文件。最好使用“file”命令来确定文件的可执行类型。 - Kenster
没错,使用 file 命令的响应来进行 shabang grepping 有点笨拙。我之前不知道这个方法,谢谢你。 - ДМИТРИЙ МАЛИКОВ

0

这对我很有用,想分享一下...

find ./ -type f -name "*" -exec sh -c '
    case "$(head -n 1 "$1")" in
      ?ELF*) exit 0;;
      MZ*) exit 0;;
      #!*/ocamlrun*)exit0;;
    esac
exit 1
' sh {} \; -print

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接