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 application’s path from command line?
For example, I have git installed on my system. But I don’t remember where I installed it, so which command is fit to find this out?
Just in case, command -v and which worked in Linux Alpine 3.16.2 (Docker image). whereis and locate did not — not installed.
5 Answers 5
If it is in your path, then you can run either type git or which git . The which command has had problems getting the proper path (confusion between environment and dot files). For type , you can get just the path with the -p argument.
If it is not in your path, then it’s best to look for it with locate -b git It will find anything named ‘git’. It’ll be a long list, so might be good to qualify it with locate -b git | fgrep -w bin .
I use locate endlessly (it is very fast), but for those unaware of it, locate is only as up to date as its most recent database update, which is automatically run daily on my Ubuntu. The refresh command is sudo updatedb . Also locate has built-in regex capability, so commands like this works: locate -br «^git$» . -b` means restrict the search to just the basename . or without the -b , it searches the full pathname .. Also, it only searches paths you have configured it to search.. there is no command-line control of this other than your regex filters.
@Gilles, that’s funny for me the behavior is exactly the opposite: type is a shell builtin that tells me aliases and such, and which is an external program that shows me the path to an executable. although if there’s a builtin that gets in the way that executable won’t get called.
@quodlibetor The problems with which are that it doesn’t know about shell built-ins and functions (which is relevant when you’re wondering what typing the command will do), and it uses a different $PATH on some systems.
Как узнать путь до исполняемого файла в 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