How to find all binary executables recursively within a directory?

You might try the file utility. According to the manpage:

The magic tests are used to check for files with data in particular fixed formats. The canonical example of this is a binary executable (compiled program) a.out file, whose format is defined in , and possibly in the standard include directory.

You might have to play around with the regular expression but something like:

$ find -type f -executable -exec file -i '{}' \; | grep 'x-executable; charset=binary'

file has lots of options, so you might want to take a closer look at the man page. I used the first option I found that seemed to output easily-to-grep output.


Here's a way to exclude scripts, i.e., files whose first two characters are #!:

find -type f -executable -exec sh -c 'test "$(head -c 2 "$1")" != "#!"' sh {} \; -print

For some kinds of files, it's not clear whether you want them classified as scripts or binary, for example bytecode files. Depending on how things are set up, these may or may not start with #!. If these matter to you, you'll have to make the inner shell script more complex. For example, here's how you might include ELF binaries and Mono executables and Objective Caml bytecode programs but not other kinds of executables like shell scripts or perl scripts or JVM bytecode programs:

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

Just in case you find yourself on a system with a downlevel find (there are still, as I write, a lotta science clusters running RHEL5!) without the rights to update: instead of

find /mypath/ -executable -type f

in the above excellent answers, you can do, e.g.,

find /mypath/h -type f -perm -u+x

which searches on permission bits. Unfortunately the above only finds files for which the user has executable, but that usually works for me.

Tags:

Binary

Find

Files