How to search for all SUID/SGID files

find

All the howtos that I find on the web states:

Find all SUID files:
find / -perm -4000 -print
Find all SGID files:
find / -perm -2000 -print 

But that is not true. See:

$ ls -lah test
-r-sr-xr-x  1 user  user     0B Jan 24 22:47 test
$ 
$ 
$ stat -x test | grep Mode
  Mode: (4555/-r-sr-xr-x)         Uid: ( 1000/    user)  Gid: ( 1000/    user)
$ 
$ 
$ find test -perm 4000
$ find test -perm 2000
$

Question: So what is the truth? How can I really list all the SUID/SGID files?

Best Answer

If you want to test for any of the bits, use /. I.e. for your use case:

find "$DIRECTORY" -perm /4000

and:

find "$DIRECTORY" -perm /2000

or combined:

find "$DIRECTORY" -perm /6000

You may use both folders and files as argument for GNU find.

Another, IMO better readable, approach is using the mnemonic shortcuts. I.e.:

find "$DIRECTORY" -perm /u=s,g=s

Caveat emptor

Keep in mind that the variants of find vary. They may also behave differently. Always read the friendly manual (RTFM).

Related Question