Skip to content
Visual explainer 2h 30m to learn 4 steps

Files, links & find

Create, copy, move and link files and locate anything with find.

By Invicly Tech, , in Linux Administration (RHCSA-style). About 11 minutes to read.

Topic 5 of 42

In short

cp, mv, rm and ln are daily tools, and find is how you locate files by name, size, owner, permissions or age anywhere on the system. find can also act on what it finds, which makes it a frequent RHCSA task, such as copying all files owned by a user into a directory.

Explained simply

Most admin work starts with moving files around: copying a config before you change it, renaming a log, removing old releases. The commands are short: cp copies, mv moves or renames, rm removes and mkdir creates a directory. There is no recycle bin on a server, so rm is final.

A link is a second way to reach a file. A symbolic link (symlink) is a tiny file that holds a path, like a shortcut on a desktop. A hard link is a second name for exactly the same file data. Admins use symlinks all the time, for example to point current at the newest version of an app.

find is the search tool. You tell it where to start and what to look for: a name, a size, an owner, an age. It walks through every folder below that point and prints each match. It can also run a command on every file it finds, such as copying, compressing or deleting.

These tools are simple, but small mistakes are costly. A good habit is to look first (print the list), then act (run the real command), and keep a copy of anything you change.

Press Play on a diagram to walk through it one step at a time.

FlowHow a find command reads
  1. Step 1
    Start point

    Where to search, such as / or /var/log.

  2. Step 2
    Tests

    -name, -user, -size +100M, -mtime -7, -perm.

  3. Step 3
    Operators

    Tests are ANDed; use -o for OR.

  4. Step 4
    Action

    -print by default, or -exec cmd {} \; or -delete.

MapOne inode, several names
inode 1312 (the data)
  • /srv/data/report.csv
    • Hard link, link count 2
  • /srv/archive/report.csv
    • Hard link, same inode
  • /home/ana/latest.csv
    • Symlink: stores the path /srv/data/report.csv
    • Own inode, breaks if that name is removed

In depth

Inodes: what a file really is

On ext4 and xfs, a file's data and details (owner, mode, size, timestamps) live in a structure called an inode, identified by a number. The file's name is not in the inode. A directory is just a list that maps names to inode numbers. ls -i shows those numbers.

A hard link adds another name that points to the same inode. The second column of ls -l is the link count. The data is only freed when the count reaches zero and no process still has the file open. Because inode numbers are only unique inside one file system, hard links cannot cross file systems, and you cannot hard link a directory.

A symlink is a separate small file that stores a path as text. It can point anywhere, even across file systems, and it breaks (dangles) if the target is removed.

CompareHard link vs symbolic link
Hard link
  • Same inode as the original
  • Works if the original name is deleted
  • Same file system only
  • Not allowed for directories
Symbolic link
  • Own inode that stores a path
  • Breaks if the target is deleted
  • Can cross file systems
  • Can point to directories

Copy, move and remove without surprises

mv inside one file system is only a rename: the inode stays the same, so it is instant even for a 50 GB file. Across file systems, mv has to copy the data and then delete the original. cp makes a new file with you as the owner and fresh timestamps; cp -a keeps owner, mode, timestamps, links and extended attributes.

This matters for SELinux on RHEL. mv keeps the file's old security label, while cp gives the copy the label of its new directory. A file moved from your home into /var/www/html can therefore be blocked by SELinux until you run restorecon on it.

For safety, cp -i and mv -i ask before overwriting, and -n never overwrites. rm -I asks once before removing many files. To remove a file whose name starts with a dash, use rm -- -file or rm ./-file.

  • mkdir -p creates parent directories and does not fail if it exists
  • cp -a /etc /root/etc-backup keeps a faithful copy
  • rmdir only removes empty directories, which makes it safe

How find reads its expression

find checks every file against the expression from left to right and stops as soon as the result is known. Tests next to each other are joined by AND. -o means OR, ! means NOT, and parentheses group tests but must be escaped from the shell: find . \( -name '*.log' -o -name '*.gz' \) -size +10M.

Numbers have rules. +n means more than n, -n means less than n, and n means exactly n. -mtime counts whole 24-hour periods, so -mtime +7 means modified more than 7 full days ago. -mmin works in minutes. -size rounds up to the unit, so -size -1M only matches empty files; use -size -1024k instead.

Other useful tests: -type f, d or l, -user and -group, -nouser (files left behind by a deleted account), -perm, -newer file, and -maxdepth n to limit how deep find goes.

  • -iname matches names without caring about case
  • -empty finds empty files and directories
  • -xdev stays on one file system, handy when searching /

Acting on results: -exec, + and xargs

-exec cmd {} \; runs cmd once per file, with {} replaced by the file name. -exec cmd {} + collects many names and runs cmd far fewer times, which is much faster on thousands of files. -ok works like -exec but asks before each one.

-delete removes matches without starting rm at all, but its position matters: find evaluates left to right, so find . -delete -name '*.tmp' deletes everything before it ever checks the name. Always put -delete last and run the same command with -print first.

When piping file names to xargs, names with spaces or newlines break the list. Use find ... -print0 | xargs -0 cmd, which separates names with a null byte that can never appear in a file name.

CompareThree ways to run a command on find results
-exec cmd {} \;
  • One process per file
  • Simple and safe with any name
  • Slow on many files
-exec cmd {} +
  • Many files per process
  • Much faster
  • {} must be last before +
-print0 | xargs -0
  • Safe with spaces and newlines
  • xargs -P runs jobs in parallel
  • Good for long pipelines

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Copy, move and remove files safely~40m
  2. 2
    Create hard and symbolic links~40m
  3. 3
    Find files by name, size, owner, time~40m
  4. 4
    Run actions on find results~40m

Key points

  • cp -a preserves ownership, permissions and timestamps.
  • rm -r has no undo; use rm -ri when unsure.
  • ln -s target linkname creates a symlink; ln without -s creates a hard link.
  • Add 2>/dev/null to find runs over / to hide permission errors.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
mkdir -p /root/found
find / -user harry -type f -exec cp -a {} /root/found/ \; 2>/dev/null
find /var/log -name "*.log" -size +50M -mtime -7
find /etc -newer /etc/hostname -type f | head
ln -s /srv/web/current /var/www/html

Copy every file owned by harry, find big recent logs, create a symlink.

Clean up old application logs safely

/var/log/myapp is filling up. Policy says compressed logs older than 30 days can go. Step 1: list matches with sizes so you can see what would be removed. Step 2: total the space you will free. Step 3: run the same expression with -delete at the end. Step 4: check the result with du. Keeping the test command and the delete command identical, apart from the last action, is what makes this safe.

bash
cd /var/log/myapp
sudo find . -name '*.gz' -mtime +30 -type f -printf '%TY-%Tm-%Td %s %p\n' | sort
sudo find . -name '*.gz' -mtime +30 -type f -printf '%s\n' | awk '{s+=$1} END {print s/1048576 " MB"}'
sudo find . -name '*.gz' -mtime +30 -type f -delete
sudo du -sh .

Switch app releases with a symlink

Each release of an app is unpacked into its own folder, and the web server always serves /srv/app/current. Step 1: unpack the new release into releases/2.4.0. Step 2: create the new link under a temporary name. Step 3: rename it over current with mv -T, which replaces the link in one step, so no request ever sees a missing path. Rolling back is the same two commands pointing at the old folder. ln -sfn also works but removes and recreates the link, leaving a tiny gap.

bash
cd /srv/app
ls releases
# 2.3.1  2.4.0
ln -s releases/2.4.0 current.tmp
mv -T current.tmp current
ls -l current
# current -> releases/2.4.0
readlink -f current          # /srv/app/releases/2.4.0

Quick reference

  • ls -li shows inode numbers and the link count of each file
  • cp -a src dst keeps owner, mode, timestamps and links
  • mv keeps the SELinux label; run restorecon -v file after moving into a web or service directory
  • find / -xdev -size +500M -type f 2>/dev/null finds big files on the root file system only
  • find /home -nouser lists files whose owner account was deleted
  • find . -name '*.tmp' -print first, then replace -print with -delete
  • find . -type f -print0 | xargs -0 grep -l TODO handles names with spaces
  • A relative symlink target is resolved from the link's own directory, not your current one

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A file has a link count of 2. You delete one of its names with rm. What happens to the data?

Question 2

2Which command finds files modified more than 7 full days ago?

Question 3

3Why is find . -delete -name '*.tmp' dangerous?

Question 4

4Why can you not create a hard link from /home/a.txt to /data/a.txt when /data is a different disk?

Question 5

5On RHEL, you mv index.html from your home into /var/www/html and Apache gets permission denied. What is the likely fix?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a file, a hard link and a symlink to it. Delete the original name and show which link still works.

  2. Exercise 2medium

    Find all regular files under /etc that are larger than 100 KiB and were changed in the last 30 days. Show their sizes in human-readable form, biggest first.

  3. Exercise 3hard

    Copy every file owned by user harry from anywhere on the system into /root/harry-files, keeping the original directory structure and attributes, without crossing into /proc or other mounted file systems.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between cp -r and cp -a?
cp -r copies directories recursively, but the copies get you as owner and new timestamps. cp -a copies recursively and keeps owner, mode, timestamps, symlinks and extended attributes.
Can I undo rm?
Not reliably. There is no trash bin on the command line, so keep backups or snapshots and use rm -i or rm -I when you are unsure.
Is a symlink the same as a Windows shortcut?
Close. Both point to another path, but a symlink is handled by the kernel, so every program follows it automatically, not just the file manager.
Why does find print Permission denied so often?
As a normal user you cannot read many system directories. Run it with sudo, or add 2>/dev/null to hide those errors.

Go deeper

ShareXLinkedInWhatsApp