Authors Top

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

The find command is a common Linux command to search for files. Using this command, we can search files by various attributes, such as filename, type, and owner.

In this quick tutorial, we’ll learn Linux commands that allow us to search for files that are not owned by a specific user.

2. Our Example

To explain how to find files not owned by a user more clearly, let’s first create a directory with some sub-directories and files.

We’ll use the tree command with the options -upf to print our example in a directory structure:

$ tree -upf
.
├── [drwxr--r-- guest   ]  ./guest_dir
│   └── [-rw-r--r-- guest   ]  ./guest_dir/my_file.txt
├── [-rw-r--r-- guest   ]  ./guest_file.png
├── [-rw-r--r-- kent    ]  ./kent_file.txt
└── [-rw-r--r-- root    ]  ./root_file.doc

1 directory, 4 files

Let’s introduce the three options we passed to tree. We let the tree command print permission flags (p), the owner of the file (u), and the full path prefixes (f).

Under our example directory, the files and directories belong to three different users: root, kent, and guest.

Now let’s address how to search files not owned by a user.

3. Find Files by (or Not by) a Specific User

If we want to find files owned by a user, we can use the -user <USERNAME> test of the find command. Let’s say we need to find all files owned by the user guest:

$ find . -user guest
./guest_dir
./guest_dir/my_file.txt
./guest_file.png

As the output above shows, all the directories and files owned by the user guest have been listed.

To search files not owned by a user, we need to negate the test in the search above. The find command allows us to add the ‘!’ character to negate the test expression in front of a test.

Now, let’s find all files not owned by the user guest under our example directory:

$ find . ! -user guest
.
./root_file.doc
./kent_file.txt

Good, our problem has been solved.

Apart from the -user test, we can also use the “!” expression with other tests in the find command.

For example, the following command will find all files whose filenames don’t match the given pattern *.txt:

$ find . ! -name *.txt
.
./guest_file.png
./root_file.doc
./guest_dir

4. Conclusion

In this quick article, we’ve learned how to search files not owned by a particular user using the find command.

Authors Bottom

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!