Search for executable files using find command
Not all implementations of find are created equal. The option recommended by @sje397 and @William may not be available. It’s better to use the accepted solution shown below.
Me dislikes all proposals shown below which are based on file permissions. Argumentation: for my GNU operating system (Ubuntu) it is possible to set «x» (executable) flag for for instance ASCII text file. No mimics prevented this operation from successful completion. It needs just small mistake/bug for multiple non-intentioned files to get x flag assigned. Therefore gniourf_gniourf’ solutions is my personal favorite. It has however that drawback that for cross-compiled executables needs an emulator or target device.
10 Answers 10
On GNU versions of find you can use -executable :
find . -type f -executable -print
For BSD versions of find, you can use -perm with + and an octal mask:
find . -type f -perm +111 -print
In this context «+» means «any of these bits are set» and 111 is the execute bits.
Note that this is not identical to the -executable predicate in GNU find. In particular, -executable tests that the file can be executed by the current user, while -perm +111 just tests if any execute permissions are set.
Older versions of GNU find also support the -perm +111 syntax, but as of 4.5.12 this syntax is no longer supported. Instead, you can use -perm /111 to get this behavior.
@sourcejedi Thanks. I was actually only talking about non-GNU versions of find (BSD, in particular) but older versions of GNU find actually did support that syntax too. In newer versions you’ll have to use / instead of + . See the updated answer for more details.
It took me a while to understand the implications of «not identical to the -executable predicate» and «just tests if any execute permissions are set»: It means that -perm +111 may yield false positives, i.e., files that the current user cannot actually execute. There’s no way to emulate -executable by testing permissions alone, because what’s needed is to relate the file’s user and group identity to the current user’s.
Tip of the hat to @gniourf_gniourf for clearing up a fundamental misconception.
This answer attempts to provide an overview of the existing answers and to discuss their subtleties and relative merits as well as to provide background information, especially with respect to portability.
Finding files that are executable can refer to two distinct use cases:
- user-centric: find files that are executable by the current user.
- file-centric: find files that have (one or more) executable permission bits set.
Note that in either scenario it may make sense to use find -L . instead of just find . in order to also find symlinks to executables.
Note that the simplest file-centric case — looking for executables with the executable permissions bit set for ALL three security principals (user, group, other) — will typically, but not necessarily yield the same results as the user-centric scenario — and it’s important to understand the difference.
User-centric ( -executable )
- The accepted answer commendably recommends -executable , IF GNU find is available.
- GNU find comes with most Linux distros
- By contrast, BSD-based platforms, including macOS, come with BSD find, which is less powerful.
find . -type f -perm -111 # or: find . -type f -perm -a=x
find . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \) -exec test -x <> \; -print
File-centric ( -perm )
- To answer file-centric questions, it issufficient to use the POSIX-compliant -perm primary (known as a test in GNU find terminology).
- -perm allows you to test for any file permissions, not just executability.
- Permissions are specified as either octal or symbolic modes. Octal modes are octal numbers (e.g., 111 ), whereas symbolic modes are strings (e.g., a=x ).
- Symbolic modes identify the security principals as u (user), g (group) and o (other), or a to refer to all three. Permissions are expressed as x for executable, for instance, and assigned to principals using operators = , + and — ; for a full discussion, including of octal modes, see the POSIX spec for the chmod utility.
- In the context of find :
- Prefixing a mode with — (e.g., -ug=x ) means: match files that have all the permissions specified (but matching files may have additional permissions).
- Having NO prefix (e.g. 755 ) means: match files that have this full, exact set of permissions.
- Caveat: Both GNU find and BSD find implement an additional, nonstandard prefix with are-ANY-of-the-specified-permission-bits-set logic, but do so with incompatible syntax:
- BSD find: +
- GNU find: / [2]
File-centric command examples
- The following examples are POSIX-compliant, meaning they should work in any POSIX-compatible implementation, including GNU find and BSD find; specifically, this requires:
- NOT using nonstandard mode prefixes + or / .
- Using the POSIX forms of the logical-operator primaries:
- ! for NOT (GNU find and BSD find also allow -not ); note that \! is used in the examples so as to protect ! from shell history expansions
- -a for AND (GNU find and BSD find also allow -and )
- -o for OR (GNU find and BSD find also allow -or )
- With mode prefix — , the = and + operators can be used interchangeably (e.g., -u=x is equivalent to -u+x — unless you apply -x later, but there’s no point in doing that).
- Use , to join partial modes; AND logic is implied; e.g., -u=x,g=x means that both the user and the group executable bit must be set.
- Modes cannot themselves express negative matching in the sense of «match only if this bit is NOT set»; you must use a separate -perm expression with the NOT primary, ! .
- -L instructs find to evaluate the targets of symlinks instead of the symlinks themselves; therefore, without -L , -type f would ignore symlinks altogether.
# Match files that have ALL executable bits set - for ALL 3 security # principals (u (user), g (group), o (others)) and are therefore executable # by *anyone*. # This is the typical case, and applies to executables in _system_ locations # (e.g., /bin) and user-installed executables in _shared_ locations # (e.g., /usr/local/bin), for instance. find -L . -type f -perm -a=x # -a=x is the same as -ugo=x # The POSIX-compliant equivalent of `-perm +111` from the accepted answer: # Match files that have ANY executable bit set. # Note the need to group the permission tests using parentheses. find -L . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \) # A somewhat contrived example to demonstrate the use of a multi-principial # mode (comma-separated clauses) and negation: # Match files that have _both_ the user and group executable bit set, while # also _not_ having the other executable bit set. find -L . -type f -perm -u=x,g=x \! -perm -o=x
[1] Description of -executable from man find as of GNU find 4.4.2:
Matches files which are executable and directories which are searchable (in a file name resolution sense). This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client’s kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed.
[2] GNU find versions older than 4.5.12 also allowed prefix + , but this was first deprecated and eventually removed, because combining + with symbolic modes yields likely yields unexpected results due to being interpreted as an exact permissions mask. If you (a) run on a version before 4.5.12 and (b) restrict yourself to octal modes only, you could get away with using + with both GNU find and BSD find, but it’s not a good idea.
How to find all binary executables recursively within a directory?
all executable files are listed (excluding directories), and including executable script file (like script.sh, etc). What I want to do is list only binary executable files.
4 Answers 4
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.
I’d say use find -type f -executable -exec sh -c «file -i ‘<>‘ | grep -q ‘x-executable; charset=binary'» \; -print . It will only give you files (and thus can be passed to the next command he wants to run)
serverfault.com/a/584595/211551 solution finds files that are NOT marked executable but are executable.
On OS X, you can install GNU find with brew install findutils or sudo port install findutils and then you can run an invocation like this to a similar effect: gfind . -type f -executable -exec file ‘<>‘ \; | grep -i execut
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
Как узнать путь до исполняемого файла в Linux?
Как в Linux узнать путь до исполняемого файла? В виндовс, например, на ярлыке или в bin/app.exe можно через свойство посмотреть Интересуюсь с целью создавать *.desktop ярлыки для заполнениями ими рабочего стола 🗔, так как способ «добавить в избранное» мне не подходит и получается рабочий стол пустой 😔
Для создания *.desktop нет необходимости указывать полный путь. Посмотрите примеры в /usr/share/applications
3 ответа 3
Я по факту могу найти приложение в диспетчере приложений, можно ли как-то оттуда взять этот путь? Или лучше и правильнее поискать путь к .exe в папках типа как в Windows —> C/Program FIles/app_folder/bin/app.exe ?
Внизу слева есть кнопка «Показать приложения», я про это имел в виду, оттуда бы как-то брать пути, там же ярлыки и их на рабочий стол хочу закидывать : )
Если вы знаете имя исполняемого файла, который выполняется в текущий момент, то полный путь к исполняемому можно узнать вот так:
pgrep | while read pid; do echo -ne "$pid\t"; readlink -f /proc/$pid/exe; done
Например, вывод для исполняемого процесса gopls (сервер go для VS Code):
pgrep gopls | while read pid; do echo -ne "$pid\t"; readlink -f /proc/$pid/exe; done 30880 /mnt/drive2/home2/user/go/bin/gopls
Набрав в командной строке
whereis locates the binary, source and manual files for the specified command names. The supplied names are first stripped of leading pathname components and any (single) trailing extension of the form .ext (for example: .c) Prefixes of s. resulting from use of source code control are also dealt with. whereis then attempts to locate the desired program in the standard Linux places, and in the places specified by $PATH and $MANPATH.
- GNU find comes with most Linux distros