# Work with files safely on Linux (cp, mv, rm, find, grep)

> Working with files safely on Linux means checking where you are with pwd, previewing with ls or find before you delete, and never running rm -rf on a path you have not read twice.

URL: https://levelrail.com/learn/linux/work-with-files-safely/
Updated: 2026-11-27

Files on a Linux server do not go to a trash folder when you delete them. `rm` removes the name and the data is gone, and a stray space or a wrong directory can erase a site in a second. The safe habit is simple: know where you are, look before you act, and keep destructive flags for paths you have just verified.

## How it works

Each command acts on paths. A path is either absolute (starts with `/`, such as `/var/www/app`) or relative to your current directory (such as `app/logs`). The same relative path means different things in different folders, which is why `pwd` matters before any delete. Deleting as the [root user](https://levelrail.com/learn/glossary/#root-user)) removes the last safety net, because root can delete anything, so check [file permissions](https://levelrail.com/learn/glossary/#file-permissions)) first.

The shell expands wildcards such as `*.log` before the command runs, so `rm *.log` receives the list of matching names. Quotes stop the shell expanding, which you need when you give `find` a pattern.

Two ideas keep you safe. First, preview: use `ls`, `find` without an action, or `echo` to print what a command would touch. Second, narrow scope: delete with the most specific path you can, not a parent folder. For the directory names themselves, see [Linux filesystem layout](https://levelrail.com/learn/linux/linux-filesystem-layout/)).

## Step 1: Look around with pwd, cd and ls

```bash
pwd
ls -la
cd /var/log
cd ~
cd -
```

`pwd` prints the current directory. `ls -la` lists everything, including hidden dot files (`-a`), in long format (`-l`) with permissions, owner, size and modification time. `cd /var/log` moves there, `cd ~` goes home, and `cd -` returns to the previous directory. Add `-h` to `ls -lah` for sizes like `4.0K` and `1.2M`. To read the permission column, see [Linux file permissions explained](https://levelrail.com/learn/server-basics/linux-file-permissions-explained/)).

## Step 2: Create, copy and move

```bash
mkdir -p projects/app/logs
cp config.yml config.yml.bak
cp -r projects projects-backup
mv config.yml.bak /tmp/
mv old-name new-name
```

`mkdir -p` creates every missing parent and stays quiet if the folder exists. `cp` copies a file, and `cp -r` copies a directory and its contents. Add `-a` (`cp -a`) to keep permissions, owners and timestamps, which matters when you copy config. `mv` moves or renames in one step. If the destination file exists, `cp` and `mv` overwrite it silently. Add `-i` to be asked first: `cp -i`, `mv -i`.

A trailing slash changes the behavior of some tools. With `cp -r`, `cp -r src dest` creates `dest/src` if `dest` exists, and creates `dest` as a copy if it does not. Run `ls dest` afterwards to confirm the result.

## Step 3: Delete with care

```bash
rm file.txt
rm -i file.txt
rm -r old-folder
rmdir empty-folder
```

`rm file.txt` deletes one file. `rm -r folder` deletes a folder and everything inside. `rmdir` only removes empty folders, so it is a safe choice when you expect the folder to be empty.

> Warning: `rm -rf` deletes recursively and forcibly, with no prompt and no undo. A typo such as `rm -rf /var/www /` or `rm -rf $DIR/` with an empty `$DIR` can destroy the system. Never run it as a reflex. Before you press Enter: run `pwd`, run `ls` on the exact path, read the command aloud, and prefer `rm -r` without `-f` so errors and prompts still appear.

A safe sequence:

```bash
pwd
ls -la build/
rm -r build/
```

If you delete as root with `sudo rm -r`, the shell no longer protects you from permission errors, so slow down more, not less. Newer GNU `rm` refuses to remove `/` itself unless you pass `--no-preserve-root`, but it will still remove everything below any other path you name.

## Step 4: Find files with find

```bash
find /var/log -name "*.log"
find /var/log -type f -name "*.gz" -mtime +30
find /home/deploy -type f -size +100M
find . -iname "readme*"
```

`find PATH TESTS` walks the folder tree and prints matches. `-name` matches by name (use quotes), `-iname` ignores case, `-type f` means files only and `-type d` directories. `-mtime +30` means last modified more than 30 days ago, `-mtime -1` means within the last day. `-size +100M` means larger than 100 megabytes.

To delete matches, add `-delete`, but preview first:

```bash
find /var/log/myapp -type f -name "*.log" -mtime +30
find /var/log/myapp -type f -name "*.log" -mtime +30 -delete
```

> Warning: `-delete` is permanent, and `find` reads its options left to right. Putting `-delete` before the tests, as in `find . -delete -name "*.log"`, deletes everything. Keep `-delete` last, use a narrow starting path, and always run the same command without it first. For spaces in names and other ways to pass results on, see [pipes, redirects and xargs](https://levelrail.com/learn/linux/pipes-redirects-and-xargs/)).

## Step 5: Search inside files with grep

```bash
grep -rn "ERROR" /var/log/myapp
grep -rni "timeout" /etc/nginx
grep -rn --include="*.conf" "listen" /etc/nginx
grep -rln "password" ~/projects
```

`-r` searches folders recursively, `-n` prints line numbers, `-i` ignores case, `-l` prints only the file names, and `--include` limits the files by pattern. The output looks like `path:line:text`. If a folder is large, narrow the path first, because grep reads every file it finds. Some files need `sudo` to read, and binary files are reported as matching without printing lines.

## Check it worked

After each change, confirm instead of assuming:

```bash
pwd
ls -la projects-backup
diff -r projects projects-backup && echo "same"
```

`diff -r` prints nothing and exits successfully when two folders match, so the `echo` runs. If you deleted something, `ls` the parent folder and check that the name is gone and that its neighbors are still there.

## Edge cases and gotchas

- **Spaces in names break unquoted commands.** `rm my file.txt` tries to delete `my` and `file.txt`. Quote it: `rm "my file.txt"`.
- **Variables can be empty.** `rm -rf "$BUILD_DIR"/` with `BUILD_DIR` unset becomes `rm -rf /`. In scripts, use `set -u` or check the value first.
- **Wildcards skip hidden files.** `rm *` does not remove `.env` or `.git`. Check with `ls -a`.
- **cp overwrites without asking.** Use `cp -i` or `cp -n` when the destination might exist.
- **mv across disks copies then deletes.** Moving a big folder between mounts takes time and can fail halfway, leaving both copies partial.
- **Symlinks behave differently.** `rm link` removes the link only, and the target stays. Recursive tools such as `chmod -R` or `rsync` may follow links, so check first. Use `ls -l` to spot arrows (`->`).
- **find -mtime counts whole days.** `-mtime +7` matches files older than eight full days, because fractions are discarded. Use `-mmin` for minutes.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `rm: cannot remove 'dir': Is a directory` | You used rm without -r | Use `rm -r dir`, or `rmdir dir` if empty |
| `cp: -r not specified; omitting directory 'projects'` | cp needs -r for folders | Run `cp -r projects dest` |
| `rm: cannot remove 'file': Permission denied` | You do not own the file or its folder | Check `ls -l`, then use `sudo` only if the delete is intended |
| `mkdir: cannot create directory 'a/b': No such file or directory` | A parent folder is missing | Use `mkdir -p a/b` |
| `find: paths must precede expression: '*.log'` | The shell expanded the wildcard before find ran | Quote it: `-name "*.log"` |
| `grep: /var/log/auth.log: Permission denied` | File readable only by root or adm | Run with `sudo` or add yourself to the right group |
| `mv: cannot stat 'file': No such file or directory` | Wrong name or you are in another folder | Run `pwd` and `ls`, then retry with the right path |
| `rm: it is dangerous to operate recursively on '/'` | The path resolved to `/` | Stop, find the empty variable or typo, and do not add `--no-preserve-root` |

## Quick reference

```bash
pwd                               # where am I
ls -lah                           # list all, human sizes
mkdir -p a/b/c                    # make nested folders
cp -a src dest                    # copy, keep attributes
mv old new                        # move or rename
rm -r folder                      # delete a folder (no undo)
find . -name "*.log" -mtime +30   # preview old logs
find . -name "*.log" -mtime +30 -delete   # delete them
grep -rn "text" /path             # search inside files
```

## Related lessons

- [Essential Linux commands for servers](https://levelrail.com/learn/server-basics/essential-linux-commands-for-servers/)): the short tour these commands come from.
- [Linux file permissions explained](https://levelrail.com/learn/server-basics/linux-file-permissions-explained/)): why a delete or copy is refused.
- [Fix a full disk on a Linux server](https://levelrail.com/learn/troubleshooting/fix-a-full-disk-on-a-linux-server/)): find large files with find and clean them up safely.
- [Back up before you change things](https://levelrail.com/learn/deploy-operate/backups-and-the-3-2-1-rule/)): the real safety net when a delete goes wrong.

For a worked example of cleaning up after a deploy, see [zero-downtime deploys with Docker and rollback](https://levelrail.com/blog/zero-downtime-deploy-docker-rollback/)).

## Next

Once you can move files around, read and edit them in [read and edit files on Linux](https://levelrail.com/learn/linux/read-and-edit-files-on-linux/)).

## Frequently asked questions

### How do I delete a folder in Linux?

Use rm -r folder to remove a folder and everything in it, or rmdir folder if it is empty. There is no recycle bin, so run ls folder first and check pwd.

### Is there an undo for rm in Linux?

No. rm unlinks the file and the shell does not keep a copy. Restoring needs a backup or a filesystem snapshot, which is why you preview before you delete.

### How do I find a file by name in Linux?

Run find /path -name "name*" to search by name, or find /path -iname for a case-insensitive match. Add -type f to match files only.

### How do I search for text inside files on Linux?

Use grep -rn "text" /path to search every file under a folder recursively and print the file name and line number of each match.


## Sources

- [GNU coreutils manual](https://www.gnu.org/software/coreutils/manual/coreutils.html)
- [GNU findutils manual](https://www.gnu.org/software/findutils/manual/html_mono/find.html)
