Menu
Perform basic file management
“ls, cp, mv, rm, mkdir, touch, wildcards, find, tar, cpio, dd and gzip, bzip2 and xz: everyday file work on Linux.”
Creating, copying, moving and deleting files is the bread and butter of Linux work. You do it in the shell because it’s fast, it works over SSH, and one command can handle a thousand files. Wildcards let you name many files at once, find locates files by name, size or age, and tar, cpio and dd copy whole trees or disks.
This objective carries a lot of exam points, and the questions love details: which option makes cp recursive, what -mtime +7 means, which tar letter means xz. This byte goes through all of them.
Listing files: ls#
You’ll use ls hundreds of times a day. The long format shows the most:
ls -ltotal 4
-rw-r--r-- 1 amin amin 0 Dec 1 12:16 notes.txt
drwxr-xr-x 3 amin amin 4096 Dec 1 12:16 project
-rw-r--r-- 1 amin amin 0 Dec 1 12:16 report.pdfFrom left to right: the file type (- file, d directory, l symbolic link) and permissions, the number of hard links, the owner, the group, the size in bytes, the last modification time and the name.
| Option | Meaning |
|---|---|
-l | Long format |
-a | All files, including hidden ones (names starting with .) |
-A | Like -a, but without . and .. |
-h | Human sizes (4.0K, 12M), together with -l |
-d | Show a directory itself, not its contents (ls -ld /etc) |
-R | Recursive: list subdirectories too |
-t / -S | Sort by time / by size (newest or biggest first) |
-r | Reverse the sort order |
-i | Show inode numbers |
-F | Add a marker: / for directories, * for executables, @ for links |
ls -ltr (newest at the bottom) is a favorite for log directories.
Creating files and directories: touch and mkdir#
touch creates an empty file, or updates the timestamps of an existing one to “now”:
touch notes.txt
touch -d "2025-01-15 10:30" old.log
touch -t 202501151030 old2.log # [[CC]YY]MMDDhhmm[.ss]
ls -l old.log-rw-r--r-- 1 amin amin 0 Jan 15 2025 old.log-a changes only the access time, -m only the modification time, and -c never creates a file that doesn’t exist.
mkdir makes directories. It fails if a parent is missing, unless you add -p:
mkdir a/b/c
mkdir -p a/b/c
mkdir -m 700 privatemkdir: cannot create directory 'a/b/c': No such file or directory-p creates all missing parents (and doesn’t complain if the directory already exists). -m sets the permissions right away, and -v prints what it creates.
Copying: cp#
cp notes.txt notes.bak # copy a file
cp notes.txt report.pdf /tmp/ # several files into a directory
cp project backup # fails: it's a directory
cp -r project backup # copy a directory recursivelycp: -r not specified; omitting directory 'project'| Option | Meaning |
|---|---|
-r or -R | Recursive: copy directories with everything inside |
-a | Archive: recursive, and keep permissions, owners, timestamps and links (-dR --preserve=all) |
-p | Keep mode, ownership and timestamps |
-i | Ask before overwriting |
-f | Force: remove a destination that can’t be opened, then retry |
-u | Only copy when the source is newer than the destination |
-v | Verbose: print each file as it’s copied |
Watch the destination: if backup doesn’t exist, cp -r project backup creates backup as a copy of project. If backup already exists, you get backup/project instead. Run the same command twice and the second run nests a copy inside the first.
Tip
Use cp -a for backups. Plain cp -r gives the copies your user as owner and the current time as timestamp, which can break things you restore later.
Moving and renaming: mv#
Linux has no separate rename command for single files: you move a file to a new name.
mv notes.bak notes.old # rename
mv -v notes.old /tmp/ # move into a directory
mv project/ archive/project-2025/ # works for directories, no -r neededrenamed 'notes.old' -> '/tmp/notes.old'mv overwrites without asking by default. -i asks first, -n never overwrites, -f never asks, and -u only moves when the source is newer. Moving within one filesystem is instant (only the name changes); moving to another filesystem copies the data and deletes the original.
Deleting: rm and rmdir#
rm notes.txt # delete a file
rm -i *.log # ask for each file
rm -r old-project # delete a directory and everything inside
rm -rf build/ # recursive, never ask, ignore missing files
rmdir empty-dir # only works on empty directories
rmdir -p a/b/c # remove c, then b, then a, as long as each is emptyrmdir refuses to delete a directory that still has files in it, which makes it a safe choice for cleanup. rm without -r refuses directories:
rm: cannot remove 'backup': Is a directory
rmdir: failed to remove 'a': Directory not emptyCaution
There’s no trash can in the shell. rm deletes for good, and rm -rf won’t ask. Check a wildcard with ls or echo first: echo rm -rf /srv/app/* shows what would run.
-f, looks like an option to rm. Use rm -- -f (the -- means “no more options after this”) or rm ./-f.What kind of file is it: file#
Linux doesn’t rely on file extensions. file looks at the contents to tell you what a file really is:
file notes.txt project /etc/passwd /bin/ls backup.gznotes.txt: empty
project: directory
/etc/passwd: ASCII text
/bin/ls: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, ...
backup.gz: gzip compressed data, from Unix, original size modulo 2^32 6Wildcards: file globbing#
Globbing is how the shell turns a pattern like *.txt into a list of matching file names. The shell does this before the command runs: ls never sees *.txt, it receives file1.txt file2.txt .... That’s why globbing works the same for every command.
| Pattern | Matches | Example |
|---|---|---|
* | Any number of characters, including none | *.txt |
? | Exactly one character | file?.txt |
[abc] | One character from the set | file[123].txt |
[a-z] | One character from the range | file[0-9].txt |
[!abc] or [^abc] | One character not in the set | file[!0-9].txt |
[[:digit:]] | One character from a class (alpha, upper, lower, alnum, space) | [[:upper:]]* |
Try them with these files:
touch file1.txt file2.txt file10.txt fileA.txt data.csv notes.md .secret
ls file?.txt
ls file[0-9].txt
ls file[!0-9].txtfile1.txt file2.txt fileA.txt
file1.txt file2.txt
fileA.txtfile10.txt doesn’t match file?.txt, because ? is exactly one character. A few rules to remember:
*doesn’t match hidden files:.secretstays out ofls *. Name it with.*or.s*.*doesn’t cross/:*.txtonly looks in the current directory.- If nothing matches, Bash passes the pattern unchanged:
echo nomatch*printsnomatch*.
Brace expansion looks similar but isn’t globbing: it builds words whether or not files exist. It’s very handy for making several things at once:
mkdir -p project/{src,docs,tests}
cp config.yml{,.bak} # same as: cp config.yml config.yml.bak
echo img{1..3}.pngimg1.png img2.png img3.pngFinding files: find#
find walks a directory tree and tests each file against conditions you give it:
find [where to start] [tests] [action]find /etc -name "*.conf"
find . -type d
find /var/log -name "*.log" -mtime +7
find / -type f -size +100M 2>/dev/nullQuote the pattern in -name "*.conf". Without quotes, the shell may expand the * itself before find ever sees it.
| Test | Matches |
|---|---|
-name "*.log" / -iname | File name pattern (-iname ignores case) |
-type f | Type: f file, d directory, l symlink, b block device, c character device, p named pipe, s socket |
-size +10M | Bigger than 10 MiB. -size -1k smaller. Units: c bytes, k, M, G |
-mtime -7 | Content modified less than 7 days ago (+7 more than 7, 7 exactly 7) |
-atime, -ctime | Same, for access time and status-change time |
-mmin -30 | Modified less than 30 minutes ago |
-newer file | Modified more recently than file |
-user amin, -group dev | Owned by that user or group |
-perm -4000 | Has these permission bits set (here: SUID) |
-empty | Empty file or directory |
-maxdepth 1 | Don’t go deeper than this many levels (put it first) |
Tests are combined with AND by default. Use -o for OR, ! for NOT, and escaped parentheses to group:
find . -name "*.c" -o -name "*.h"
find . -type f ! -name "*.txt"
find . \( -name "*.tmp" -o -name "*.bak" \) -mtime +30find counts time in whole 24-hour periods and drops the fraction. So -mtime +7 really means “at least 8 full days ago”, and -mtime 0 means “within the last 24 hours”.Doing something with the results#
By default find prints the paths (-print). Other actions:
| Action | What it does |
|---|---|
-ls | Print details like ls -l |
-delete | Delete each match |
-exec cmd {} \; | Run cmd once per file; {} is replaced by the path |
-exec cmd {} + | Run cmd once with as many paths as fit (faster) |
-ok cmd {} \; | Like -exec, but ask first |
find logs -name "*.log" -exec wc -l {} +
find /tmp -type f -name "*.tmp" -mtime +7 -delete1 logs/app2.log
1 logs/app3.log
1 logs/app1.log
3 totalThe \; needs its backslash so the shell passes the ; to find instead of treating it as the end of the command.
Archives: tar#
tar (tape archive) packs a directory tree into one file, keeping names, permissions and timestamps. The original files stay where they are. You always pick one main mode and almost always -f:
| Option | Meaning |
|---|---|
-c | Create an archive |
-x | Extract an archive |
-t | List the contents |
-f file | The archive file name (put it last in a group: -cvf name.tar) |
-v | Verbose: list files as they’re processed |
-z | Compress with gzip (.tar.gz, .tgz) |
-j | Compress with bzip2 (.tar.bz2) |
-J | Compress with xz (.tar.xz) |
-C dir | Change to this directory first (extract somewhere else) |
--exclude=PATTERN | Leave matching files out |
tar -cvf project.tar project
tar -czf project.tar.gz project
tar -cJf project.tar.xz project
tar -tvf project.tar
tar -xzf project.tar.gz -C /tmp/restoreproject/
project/src/
project/src/main.c
project/src/lib/
drwxr-xr-x amin/amin 0 2026-12-01 12:16 project/
drwxr-xr-x amin/amin 0 2026-12-01 12:16 project/src/
-rw-r--r-- amin/amin 2 2026-12-01 12:16 project/src/main.c
drwxr-xr-x amin/amin 0 2026-12-01 12:16 project/src/lib/You’ll often see the old style without a dash: tar cvf project.tar project. It works the same. GNU tar also detects the compression by itself when extracting, so tar -xf project.tar.xz works without -J. To extract a single file, name it after the archive: tar -xzf project.tar.gz project/src/main.c.
Archives: cpio#
cpio (copy in, copy out) is an older archiver. Unlike tar, it doesn’t walk directories itself: it reads the list of files from standard input, usually from find or ls.
find project | cpio -ov > project.cpio # -o: copy out (create)
cpio -itv < project.cpio # -i -t: list contents
mkdir restore && cd restore
cpio -idv < ../project.cpio # -i: copy in (extract), -d: create directories| Option | Meaning |
|---|---|
-o | Copy-out mode: create an archive from a file list |
-i | Copy-in mode: extract from an archive |
-p | Pass-through: copy files to another directory without an archive |
-t | List contents (with -i) |
-d | Create leading directories when extracting |
-v | Verbose |
You rarely make cpio archives by hand, but they’re everywhere under the hood: the Linux initramfs is a cpio archive, and RPM packages contain one (rpm2cpio package.rpm | cpio -idv unpacks an RPM).
Copying raw data: dd#
dd copies bytes, block by block, from an input to an output. It doesn’t care about files or filesystems, which makes it the tool for disk images, USB sticks and boot sectors.
| Operand | Meaning |
|---|---|
if= | Input file (default: standard input) |
of= | Output file (default: standard output) |
bs= | Block size per read and write (512, 4M) |
count= | Copy only this many blocks |
skip= / seek= | Skip blocks at the start of the input / output |
status=progress | Show progress while copying |
conv= | Conversions, like ucase, notrunc or fsync |
dd if=/dev/zero of=disk.img bs=1M count=10 # 10 MiB file of zeros
sudo dd if=/dev/sda of=mbr.bin bs=512 count=1 # back up the MBR
sudo dd if=debian.iso of=/dev/sdb bs=4M status=progress conv=fsync10+0 records in
10+0 records out
10485760 bytes (10 MB, 10 MiB) copied, 0.0043 s, 2.4 GB/s“10+0 records” means 10 full blocks and 0 partial ones.
Caution
dd overwrites whatever of= points to without asking. Write an ISO to /dev/sda instead of /dev/sdb and your system disk is gone. Check the device name with lsblk first.
Compression: gzip, bzip2 and xz#
These tools compress one file at a time and replace the original with the compressed version. To compress a directory, make a tar archive first (or use tar -z, -j, -J).
| Compress | Decompress | Extension | Speed | Size |
|---|---|---|---|---|
gzip | gunzip (gzip -d) | .gz | Fastest | Biggest |
bzip2 | bunzip2 (bzip2 -d) | .bz2 | Slow | Smaller |
xz | unxz (xz -d) | .xz | Slowest to compress | Smallest |
seq 1 100000 > numbers.txt
gzip numbers.txt
ls numbers*
gunzip numbers.txt.gz
gzip -k numbers.txt; bzip2 -k numbers.txt; xz -k numbers.txt
ls -l numbers.txt*numbers.txt.gz
-rw-r--r-- 1 amin amin 588895 Dec 1 12:16 numbers.txt
-rw-r--r-- 1 amin amin 124009 Dec 1 12:16 numbers.txt.bz2
-rw-r--r-- 1 amin amin 215169 Dec 1 12:16 numbers.txt.gz
-rw-r--r-- 1 amin amin 17992 Dec 1 12:16 numbers.txt.xzThe options are almost the same for all three:
| Option | Meaning |
|---|---|
-k | Keep the original file |
-d | Decompress |
-c | Write to standard output, leave files alone (gzip -c f > f.gz) |
-1 … -9 | Faster … smaller (default is -6 for gzip and xz, -9 for bzip2) |
-l | List compressed and original size (gzip and xz) |
-t | Test the compressed file’s integrity |
-v | Verbose |
To read a compressed file without unpacking it, use zcat, bzcat or xzcat from text filters. On minimal installs, bzip2 and xz may need installing: apt install bzip2 xz-utils on Debian and Ubuntu, dnf install bzip2 xz on RHEL and Fedora.
Exam checklist#
cp -r/-Rcopies directories,cp -aalso keeps owners, permissions and timestamps.mvneeds no-r.rm -rdeletes trees,rmdironly empty directories.mkdir -pcreates missing parents;rmdir -premoves empty parents.touchcreates empty files or updates timestamps.- Globs:
*any characters,?one character,[abc],[a-z],[!a-z].*skips hidden files. The shell expands globs, not the command. findtests:-name,-iname,-type f/d/l,-size +10M,-mtime -7(newer than 7 days) or+7(older),-user,-perm. Actions:-exec cmd {} \;,-delete,-ls.tar:ccreate,xextract,tlist,ffile,vverbose,zgzip,jbzip2,Jxz,-Ctarget directory.cpioreads file names from standard input:find . | cpio -o > a.cpio,cpio -id < a.cpio.dd if= of= bs= count=copies raw blocks: disk images, MBR backups (bs=512 count=1), bootable USB sticks.gzip/bzip2/xzreplace the original (-kkeeps it). Decompress withgunzip/bunzip2/unxzor-d. xz compresses smallest, gzip fastest.fileidentifies a file by its contents, not its name.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(lpic-103): Perform basic file management"
[main e1439f0] learn(lpic-103): Perform basic file management
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: