「find -delete」がディレクトリ内のすべてのファイルを繰り返し削除するのはなぜですか?

「find -delete」がディレクトリ内のすべてのファイルを繰り返し削除するのはなぜですか?

そのため、次のようなUnix findの動作により、膨大なコストが発生しました。

> touch foo
> touch bar
> ls  
bar  foo
> find . -name '*oo' -delete
> ls
bar
> touch baz
> ls
bar  baz
> find . -delete -name '*ar'
> ls
> #WHAAAT?

ポイントは何ですか?

ベストアンサー1

検索コマンドラインは、式を形成するために結合されたさまざまな種類のオプションで構成されています。

このfindオプション-deleteはアクションです。
つまり、これまで一致するすべてのファイルに対して実行されることを意味します。
パスの後の最初のオプションはすべてのファイルに一致します。

これは危険です。しかし、少なくともマニュアルページでは大きな警告:

~からman find:

ACTIONS
    -delete
           Delete  files; true if removal succeeded.  If the removal failed, an
           error message is issued.  If -delete fails, find's exit status  will
           be nonzero (when it eventually exits).  Use of -delete automatically
           turns on the -depth option.

           Warnings: Don't forget that the find command line is evaluated as an
           expression,  so  putting  -delete first will make find try to delete
           everything below the starting points you specified.  When testing  a
           find  command  line  that  you later intend to use with -delete, you
           should explicitly specify -depth in order to avoid later  surprises.
           Because  -delete  implies -depth, you cannot usefully use -prune and
           -delete together.


遠くからman find:

EXPRESSIONS
    The expression is made up of options (which affect overall operation rather
    than  the  processing  of  a  specific file, and always return true), tests
    (which return a true or false value), and actions (which have side  effects
    and  return  a  true  or false value), all separated by operators.  -and is
    assumed where the operator is omitted.

    If the expression contains no actions other than  -prune,  -print  is  per‐
    formed on all files for which the expression is true.


コマンドがfind実行する操作を試みたとき:

コマンドがどのように見えるかを確認してください。

find . -name '*ar' -delete

削除されると、まず-deleteタスクをより無害なタスクに置き換えることができます。たとえば、-flsまたは次のようになります-print

find . -name '*ar' -print

これにより、ジョブの影響を受けるファイルが印刷されます。
この例では、-printを省略できます。この場合は何もしないので、最も明白なことは暗黙的に以下を追加することです-print。 (上記の「式」セクションの2番目の段落を参照)

おすすめ記事