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.
- Updated Nov 27, 2026
- Markdown
Copy, move, delete and search files from the shell, and use a preview step so a typo cannot wipe the wrong folder.
- An Ubuntu or Debian server you can reach over SSH
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 removes the last safety net, because root can delete anything, so check 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.
Step 1: Look around with pwd, cd and ls#
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.
Step 2: Create, copy and move#
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-namemkdir -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#
rm file.txt
rm -i file.txt
rm -r old-folder
rmdir empty-folderrm 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 -rfdeletes recursively and forcibly, with no prompt and no undo. A typo such asrm -rf /var/www /orrm -rf $DIR/with an empty$DIRcan destroy the system. Never run it as a reflex. Before you press Enter: runpwd, runlson the exact path, read the command aloud, and preferrm -rwithout-fso errors and prompts still appear.
A safe sequence:
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#
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:
find /var/log/myapp -type f -name "*.log" -mtime +30
find /var/log/myapp -type f -name "*.log" -mtime +30 -deleteWarning:
-deleteis permanent, andfindreads its options left to right. Putting-deletebefore the tests, as infind . -delete -name "*.log", deletes everything. Keep-deletelast, 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.
Step 5: Search inside files with grep#
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:
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.txttries to deletemyandfile.txt. Quote it:rm "my file.txt". - Variables can be empty.
rm -rf "$BUILD_DIR"/withBUILD_DIRunset becomesrm -rf /. In scripts, useset -uor check the value first. - Wildcards skip hidden files.
rm *does not remove.envor.git. Check withls -a. - cp overwrites without asking. Use
cp -iorcp -nwhen 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 linkremoves the link only, and the target stays. Recursive tools such aschmod -Rorrsyncmay follow links, so check first. Usels -lto spot arrows (->). - find -mtime counts whole days.
-mtime +7matches files older than eight full days, because fractions are discarded. Use-mminfor 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#
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 filesRelated lessons#
- Essential Linux commands for servers: the short tour these commands come from.
- Linux file permissions explained: why a delete or copy is refused.
- Fix a full disk on a Linux server: find large files with find and clean them up safely.
- Back up before you change things: 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.
Next#
Once you can move files around, read and edit them in read and edit files on Linux.
Try it: Preview, then delete
Practice the safe order: look around, copy, search, preview a cleanup, then remove.
Want a real machine? Free browser labs: Killercoda
Check what you learned
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
Keep going: guides and tutorials
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.