DEV Community

Cover image for File and Directory Management in Linux
Yeasin's
Yeasin's

Posted on

File and Directory Management in Linux

Everything in Linux is a file. Your documents are files, your programs are files, your terminal is a file, even your hardware devices are represented as files. This single idea is what makes Linux so powerful and consistent — but it also means that if you want to be productive on the command line, you must learn to manage files and directories fluently.

In this guide, we'll cover the essential commands and concepts: navigating the filesystem, creating, copying, moving, and deleting files, understanding the directory structure, finding files fast, and — critically — how to avoid the mistakes that destroy data.


The Linux Directory Structure: Start Here

Before touching any command, you need a map. Unlike Windows with its C:\ drive, Linux has one single tree that starts at the root directory, written as /.

ls /
Enter fullscreen mode Exit fullscreen mode
bin   dev  home  lib32  media  opt   root  sbin  srv  tmp  var
boot  etc  lib   lib64  mnt    proc  run   snap  sys  usr
Enter fullscreen mode Exit fullscreen mode

The important ones to know:

Directory What lives here
/home Personal folders of normal users (/home/yeasin)
/root Home directory of the root user
/etc System-wide configuration files
/var Variable data: logs (/var/log), caches, websites
/tmp Temporary files — often cleared on reboot
/usr Installed programs and their files
/opt Third-party / manually installed software
/dev Device files (disks, terminals appear here)
/proc Virtual files exposing kernel and process info

Note: Unlike Windows, Linux uses / (forward slash) as the separator, and paths are case-sensitive. /home/Yeasin and /home/yeasin are two different paths.

Absolute vs relative paths

There are two ways to write a path:

  • Absolute path — starts from /: /home/yeasin/projects/app.js (works from anywhere)
  • Relative path — starts from your current location: projects/app.js

Two special names help you move around:

  • . — the current directory
  • .. — the parent directory (one level up)

So cd .. moves up, and cd ../.. moves up two levels.


Navigating: pwd, ls, and cd

Always know where you are before you act. Three commands handle all navigation:

Where am I? — pwd

pwd
Enter fullscreen mode Exit fullscreen mode
/home/yeasin
Enter fullscreen mode Exit fullscreen mode

pwd (print working directory) shows your current location in the tree. It sounds trivial, but in long terminal sessions with multiple tabs, it saves you from running commands in the wrong place.

What's here? — ls

ls            # list names only
ls -l         # long format: permissions, owner, size, date
ls -a         # include hidden files (starting with .)
ls -la        # long + hidden, the everyday combo
ls -lh        # long + human-readable sizes (K, M, G)
ls -lt        # sorted by modification time, newest first
Enter fullscreen mode Exit fullscreen mode

Example output:

total 24K
drwxr-xr-x 3 yeasin yeasin 4.0K Oct 17 12:00 projects
-rw-r--r-- 1 yeasin yeasin 2.2K Oct 16 18:42 notes.txt
drwxr-xr-x 2 yeasin yeasin 4.0K Oct 15 09:10 .ssh
Enter fullscreen mode Exit fullscreen mode

Two useful extras: ls -R lists directories recursively, and ls /etc lists a directory without entering it.

Moving around — cd

cd /var/log        # go to an absolute path
cd projects        # go into a subdirectory (relative)
cd ..              # go up one level
cd ~               # go to your home directory
cd -               # go back to the previous directory
cd                 # no argument = home directory too
Enter fullscreen mode Exit fullscreen mode

cd - is a small trick worth remembering: it toggles between your last two locations, like a channel-swap button.


Creating Files and Directories

Touch — create an empty file

touch notes.txt
touch a.txt b.txt c.txt
Enter fullscreen mode Exit fullscreen mode

touch also has a second job: it updates the timestamp of an existing file without changing its content.

mkdir — create directories

mkdir projects
mkdir projects/src projects/docs    # multiple at once
mkdir -p projects/src/components    # create parents as needed
Enter fullscreen mode Exit fullscreen mode

The -p flag is the one to remember. Without it, creating projects/src/components fails if projects doesn't exist yet. With -p, the whole chain is created in one shot.

Creating files with content

For a quick file with text, you don't even need an editor:

echo "Hello, world" > hello.txt      # overwrite
echo "Second line" >> hello.txt      # append
Enter fullscreen mode Exit fullscreen mode

Copying and Moving

cp — copy

cp notes.txt backup.txt             # copy a file
cp -r projects projects-backup      # copy a directory (recursive required)
cp -i notes.txt old.txt            # ask before overwriting
cp *.txt /tmp/                      # copy all .txt files somewhere
Enter fullscreen mode Exit fullscreen mode

Warning: cp overwrites existing files silently by default. If old.txt already exists, it's gone with no confirmation. Use -i (interactive) whenever you're unsure. A safer habit for a session: alias cp='cp -i'.

Note that cp for a directory requires -r — without it, cp refuses to copy directories. This is a safety feature, not a limitation.

mv — move and rename

mv is two commands in one — it moves files and it renames them (renaming is moving to a new name):

mv notes.txt documents/        # move into a directory
mv notes.txt todo.txt          # rename
mv -i old.txt documents/      # ask before overwriting
mv projects/ archive/         # move a whole directory
Enter fullscreen mode Exit fullscreen mode

mv is fast even for huge files, because moving on the same filesystem doesn't copy data — it just updates the pointer.


Deleting: rm, rmdir, and Staying Safe

This is the part where mistakes hurt, so let's be careful and precise.

rm — delete files

rm notes.txt          # delete one file — no recycle bin, no undo
rm -i notes.txt       # ask for confirmation first
rm -r projects        # delete a directory and everything inside
rm -f stuck.txt      # force: ignore warnings, don't ask
Enter fullscreen mode Exit fullscreen mode

Three facts every Linux user must internalize:

  1. There is no trash bin. rm is permanent.
  2. rm -r is powerful enough to delete an entire system. That's why sudo rm -rf / is the most infamous command in Linux — it means "delete everything, don't ask, no exceptions."
  3. rm doesn't ask for confirmation by default. A typo in a path can delete the wrong thing instantly.

rmdir — the cautious alternative

rmdir empty-folder
Enter fullscreen mode Exit fullscreen mode

rmdir only removes empty directories. If there's anything inside, it refuses. This makes it a great "safe" option when you expect a folder to be empty and want to be alerted if it's not.

Safer deletion patterns

A professional habit: list first, then delete.

ls projects/*.log    # see exactly what will be deleted
rm projects/*.log    # now delete it
Enter fullscreen mode Exit fullscreen mode

Even better — use -i once and build the habit:

rm -ri old-projects/
Enter fullscreen mode Exit fullscreen mode

Tip: One character in the wrong place makes rm dangerous. rm -rf projects / (with a space before the slash) would delete projects and the root filesystem. This is not a joke command — it's a real typo people have made. Always read the full command once before pressing Enter, especially with sudo.


Viewing Files

Before editing, you usually want to look inside a file:

cat notes.txt        # print the whole file
less notes.txt      # open in a pager: q to quit, / to search
head -n 20 notes.txt  # first 20 lines
tail -n 20 notes.txt  # last 20 lines
tail -f app.log      # follow a log file live as it grows
Enter fullscreen mode Exit fullscreen mode

The distinction matters for real work:

  • cat is fine for small files, but a 10,000-line log will flood your terminal.
  • less lets you scroll, search (/pattern), and quit with q.
  • tail -f is how sysadmins watch logs in real time — every new line appears as it's written. Debugging a live service? This is your window.

Finding Files: find and locate

find — powerful, real-time search

find /var/log -name "*.log"             # by name
find ~ -type d -name projects            # directories only
find /etc -iname "*.conf"                # case-insensitive
find . -size +100M                       # files bigger than 100 MB
find . -mtime -7                        # modified in the last 7 days
find . -name "*.tmp" -delete             # find AND delete in one command
Enter fullscreen mode Exit fullscreen mode

find walks the actual filesystem, so it's always accurate — but can be slow on huge trees. The -delete action at the end is efficient, but treat it like rm: run the command without -delete first to preview the results.

locate — fast, database-based

sudo apt install plocate -y
locate nginx.conf
Enter fullscreen mode Exit fullscreen mode

locate answers instantly because it searches a pre-built database (updated daily, or manually with sudo updatedb). The tradeoff: very new files may not be in the database yet.


Wildcards: The Pattern Language of the Shell

Wildcards (glob patterns) are how you select many files at once — and they work with every command:

Pattern Matches
* Any number of any characters
? Exactly one character
[abc] One character: a, b, or c
*.txt All files ending in .txt
file?.log file1.log, fileA.log — but not file10.log

Real examples:

cp *.jpg /backup/
rm old-*.tmp
mv report?.pdf reports/
Enter fullscreen mode Exit fullscreen mode

Note: The shell expands the wildcard before the command runs — the command never sees the *, only the expanded list. This is why listing with ls first is a reliable preview of what a glob will touch.


A Practical Workflow: Organizing a Messy Folder

Let's combine everything into a realistic scenario. Your home directory is full of loose files:

ls ~
Enter fullscreen mode Exit fullscreen mode
app.js  index.html  notes.txt  package.json  old-report.pdf  server.js  styles.css
Enter fullscreen mode Exit fullscreen mode

Clean it up in a few commands:

mkdir -p ~/web/{src,docs,reports}          # create the structure in one line
mv *.js *.css *.html ~/web/src/            # move code files
mv notes.txt ~/web/docs/
mv old-report.pdf ~/web/reports/
Enter fullscreen mode Exit fullscreen mode

Then verify:

find ~/web -type f
Enter fullscreen mode Exit fullscreen mode
/home/yeasin/web/src/app.js
/home/yeasin/web/src/server.js
/home/yeasin/web/src/index.html
/home/yeasin/web/src/styles.css
/home/yeasin/web/docs/notes.txt
/home/yeasin/web/reports/old-report.pdf
Enter fullscreen mode Exit fullscreen mode

That {src,docs,reports} syntax is brace expansion — another shell trick worth remembering. mkdir -p a/{one,two,three} creates three subdirectories instantly.


Common Mistakes and Troubleshooting

1. "No such file or directory" — but the file is right there
Linux paths are case-sensitive: Notes.txt is not notes.txt. Use ls and tab completion (press Tab to auto-complete names) to avoid typos entirely.

2. Deleted something you needed
No recycle bin exists, so recovery depends on backups. The lesson: build the list-first habit, and use mv to a "trash" folder instead of rm for anything you might miss:

mkdir ~/.trash
mv important.txt ~/.trash/
Enter fullscreen mode Exit fullscreen mode

3. cp says "omitting directory"
You forgot -r. Directories always need cp -r.

4. Running out of space — finding the culprit

df -h                     # disk usage per filesystem
du -sh /var/* | sort -h   # which folders are big
find ~ -size +500M        # huge files in your home
Enter fullscreen mode Exit fullscreen mode

5. Permission denied
Some files belong to other users or root. Don't reflexively add sudo — first check who owns the file with ls -l, and prefer fixing ownership or location rather than escalating. (chown and chmod deserve their own article — coming next in this series.)


Summary

  • Linux has one filesystem tree starting at /, with a standard directory layout — learn /home, /etc, /var, and /tmp first.
  • Navigation is three commands: pwd (where am I), ls (what's here), cd (go there).
  • Create with touch and mkdir -p; copy with cp -r; move/rename with mv.
  • rm is permanent — there is no trash bin. List first (ls), then delete, and use -i when unsure.
  • View files with less, head/tail, and tail -f for live logs.
  • Find files with find (accurate, real-time) or locate (instant, database-based).
  • Wildcards (*, ?) work with every command and are expanded by the shell before the command runs.

Master these commands until they're muscle memory, and the command line stops feeling like a struggle — it starts feeling like home. Every sysadmin skill you learn next, from servers to security, builds on this foundation.

Top comments (1)

Collapse
 
skepagent profile image
SkepAgent •

“先列出再删除”这个习惯写得最到位,rm 没有回收站,靠事后补救根本来不及。把重要文件先 mv 到 ~/.trash 的做法我也常用,只补充一点:这个临时目录最好顺手定个清理周期,不然它会悄悄吃掉磁盘,最后反而要去查是谁占了空间。