I know I can find files using find
: find . -type f -name 'sunrise'
. Example result:
./sunrise
./events/sunrise
./astronomy/sunrise
./schedule/sunrise
I also know that I can determine the file type of a file: file sunrise
. Example result:
sunrise: PEM RSA private key
But how can I find files by file type?
For example, my-find . -type f -name 'sunrise' -filetype=bash-script
:
./astronomy/sunrise
./schedule/sunrise
Best Answer
"File types" on a Unix system are things like regular files, directories, named pipes, character special files, symbolic links etc. These are the type of files that
find
can filter on with its-type
option.The
find
utility can not by itself distinguish between a "shell script", "JPEG image file" or any other type of regular file. These types of data may however be distinguished by thefile
utility, which looks at particular signatures within the files themselves to determine their type.A common way to label the different types of data files is by their MIME type, and
file
is able to determine the MIME type of a file.Using
file
withfind
to detect the MIME type of regular files, and use that to only find shell scripts:or, using
bash
,Add
-name sunrise
before the-exec
if you wish to only detect scripts with that name.The
find
command above will find all regular files in or below the current directory, and for each such file call a short in-line shell script. This script runsfile -bi
on the found file and exits with a zero exit status if the output of that command contains the string/x-shellscript
. If the output does not contain that string, it exits with a non-zero exit status which causesfind
to continue immediately with the next file. If the file was found to be a shell script, thefind
command will proceed to output the file's pathname (the-print
at the end, which could also be replaced by some other action).The
file -bi
command will output the MIME type of the file. For a shell script on Linux (and most other systems), this would be something likewhile on systems with a slightly older variant of the
file
utility, it may beThe common bit is the
/x-shellscript
substring.Note that on macOS, you would have to use
file -bI
instead offile -bi
because of reasons (the-i
option does something quite different). The output on macOS is otherwise similar to that of a Linux system.Would you want to perform some custom action on each found shell script, you could do that with another
-exec
in place of the-print
in thefind
commands above, but it would also be possible to door, with
bash
,Related: