複数の条件を含むコマンドの検索

複数の条件を含むコマンドの検索

次のユースケースを紹介します。

[root@localCentOS71 folder]# ls -lah
total 16K
drwxr-xr-x 3 root root  4.0K Dec 22 08:52 .
drwxr-xr-x 4 root root  4.0K Dec 21 14:59 ..
-rw-r--r-- 1 root test     0 Dec 22 08:52 file
drwxr-xr-x 2 root root  4.0K Dec 21 14:59 hi
-rw-r--r-- 1 root root     0 Dec 22 08:46 .htaccess
-rw-r--r-- 1 root root   175 Dec 22 08:47 test

find実行するコマンドを呼び出そうとします。

  • 一般ファイルのみを検索
  • 所有者がルート以外の場所を見つけたり、
  • 検索グループがルートではない
  • 権限が775以外の場所を探す
  • .htaccess ファイルを除外

現在のコマンド:

find /folder -not -user root -or -not -group test -type f \( ! -iname ".htaccess" \) -or -not -perm 775

希望の出力:

/folder/test
/folder/file

実際の出力:

/folder
/folder/.htaccess
/folder/hi
/folder/test
/folder/file

ベストアンサー1

-a(省略すると、2つの述語間の暗黙の優先順位)が前にあるので、括弧-oを使用する必要があります。

find /folder ! -name .htaccess -type f \( \
   ! -user root -o ! -group test -o ! -perm 775 \)

または:

find /folder ! -name .htaccess -type f ! \( \
   -user root -group test -perm 775 \)

ファイルの操作は-name不要なので、最適化のための最初の作業を実行してください。lstat()一部のfind実装は独自に最適化を行います(内部的に述語リストを並べ替えます)。

-notとは-or非標準GNU拡張です。標準同等物!です-o

優先順位ルールのため

find /folder -not -user root -or -not -group test -type f \( 
  ! -iname ".htaccess" \) -or -not -perm 775

実際には次のように解釈できます。

find /folder \( -not -user root \) -or \
             \( -not -group test -a \
                -type f -a \
               \( ! -iname ".htaccess" \) \
             \) -or \
             \( -not -perm 775 \)

おすすめ記事