Как описано на странице руководства (ual )в find
, а на странице руководства ls
точно нет, -exec
является параметром, специфичным для find
. Вот почему -exec
работает с find
, но не с ls
.
На справочной странице find
говорится:
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is
replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these
constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified
command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the
-execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invoca‐
tions of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is al‐
lowed within the command. The command is executed in the starting directory. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run
at all. This variant of -exec always returns true.
-execdir command ;
-execdir command {} +
Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method
for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to
process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your $PATH envi‐
ronment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same
applies to having entries in $PATH which are empty or which are not absolute directory names. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands
may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true
only if command returns 0.
Команда ls
не принимает такой параметр.
Лучше всего узнать о команде, прочитав ее руководство info ls
/ info find
или man ls/man find
. Или спецификацию POSIX каждого, чтобы узнать о подмножестве, которое должно быть общим для всех различных реализаций.
Синтаксис для find
:
find [options] <file1> [<file2>...] [predicates]
(некоторые find
реализации позволяют пропускать<file1>
)
Иls
:
ls [options] [<file1> [<file2>...]]
(где [...]
обозначают необязательные части ).
Стандартные параметры состоят из одной буквы и вводятся с -
. Кто-то принимает аргументы, кто-то нет. Опции могут быть объединены в один аргумент. Например, ls -l -d
можно записать как ls -ld
.
Таким образом, вы можете видеть, что -exec
никогда не может быть опцией, потому что find
будет интерпретировать ее как-e -x -e -c
(или, возможно, -e -x ec
, если опция -x
принимает аргументы ).
Некоторые реализации инструмента поддерживают длинные параметры , но они имеют префикс --
вместо -
, чтобы избежать этого конфликта. Например, GNU find
и GNU ls
поддерживают опцию--help
.
Для find
, -exec
— это то, что POSIX называет предикатом . Это не вариант . Это часть выражения , которое идет после списка файлов и используется для определения того, какие файлы выбраны и что с ними делать.
find
также поддерживает несколько параметров (, которые идут перед списком файлов ), таких как -L
/ -H
, которые глобально влияют на его поведение.
ls
не имеет концепции предиката и выражения , используемых для выбора файлов.На его поведение влияют только опции . Нет опции, позволяющей ls
выполнять произвольные команды.
Кстати, в вашем коде есть несколько проблем:
-a
(подразумевается, если опущен )имеет приоритет над -o
, поэтому ваш -exec
будет выполняться только для *.l
файлов. См.`find `с несколькими `-именами `и `-exec `выполняет только последние совпадения имени `-`-r
вместо grep
. Это нестандартная опция, поддерживаемая некоторыми реализациями grep
для выполнения работы find
и поиска файлов внутри каталогов. Хотя, вероятно, здесь это безвредно, если ни один из файлов, найденных с помощью find
, не относится к типу каталога, это, вероятно, не нужно. {} \;
, вы запускаете один grep
для каждого файла. Это очень неэффективно, и это также означает, что grep
не будет отображать имена файлов (, если только -r
выше не пинает в)-iname
не является -стандартным расширением (вы можете найти его в info find
в вашей системе, если это расширение GNU, но вы не найдете его в спецификации POSIX ). -type
, find
сообщит о любом типе файла, а не только об обычном. Это могут быть каталоги, устройства, FIFO... Использование -type f
ограничит поиск обычными файлами. С GNU find
вы также можете использовать -xtype f
для выбора файлов, которые в конечном итоге станут обычными после разрешения символической ссылки. Чтобы решить эту проблему, вы можете:
find. -name '*.[cChl]' -type f -exec grep -in test1 /dev/null {} +