Menu

GNU and Unix Commands

Step 3 of 8 LPIC-1 103.3weight 4

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.”

View .md

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:

bash
ls -l
text
total 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.pdf

From 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.

OptionMeaning
-lLong format
-aAll files, including hidden ones (names starting with .)
-ALike -a, but without . and ..
-hHuman sizes (4.0K, 12M), together with -l
-dShow a directory itself, not its contents (ls -ld /etc)
-RRecursive: list subdirectories too
-t / -SSort by time / by size (newest or biggest first)
-rReverse the sort order
-iShow inode numbers
-FAdd 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”:

bash
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
text
-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:

bash
mkdir a/b/c
mkdir -p a/b/c
mkdir -m 700 private
text
mkdir: 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#

bash
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 recursively
text
cp: -r not specified; omitting directory 'project'
OptionMeaning
-r or -RRecursive: copy directories with everything inside
-aArchive: recursive, and keep permissions, owners, timestamps and links (-dR --preserve=all)
-pKeep mode, ownership and timestamps
-iAsk before overwriting
-fForce: remove a destination that can’t be opened, then retry
-uOnly copy when the source is newer than the destination
-vVerbose: 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.

bash
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 needed
text
renamed '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#

bash
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 empty

rmdir refuses to delete a directory that still has files in it, which makes it a safe choice for cleanup. rm without -r refuses directories:

text
rm: cannot remove 'backup': Is a directory
rmdir: failed to remove 'a': Directory not empty

Caution

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.

A file whose name starts with a dash, like -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:

bash
file notes.txt project /etc/passwd /bin/ls backup.gz
text
notes.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 6

Wildcards: 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.

PatternMatchesExample
*Any number of characters, including none*.txt
?Exactly one characterfile?.txt
[abc]One character from the setfile[123].txt
[a-z]One character from the rangefile[0-9].txt
[!abc] or [^abc]One character not in the setfile[!0-9].txt
[[:digit:]]One character from a class (alpha, upper, lower, alnum, space)[[:upper:]]*

Try them with these files:

bash
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].txt
text
file1.txt  file2.txt  fileA.txt
file1.txt  file2.txt
fileA.txt

file10.txt doesn’t match file?.txt, because ? is exactly one character. A few rules to remember:

  • * doesn’t match hidden files: .secret stays out of ls *. Name it with .* or .s*.
  • * doesn’t cross /: *.txt only looks in the current directory.
  • If nothing matches, Bash passes the pattern unchanged: echo nomatch* prints nomatch*.

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:

bash
mkdir -p project/{src,docs,tests}
cp config.yml{,.bak}               # same as: cp config.yml config.yml.bak
echo img{1..3}.png
text
img1.png img2.png img3.png

Finding files: find#

find walks a directory tree and tests each file against conditions you give it:

text
find [where to start] [tests] [action]
bash
find /etc -name "*.conf"
find . -type d
find /var/log -name "*.log" -mtime +7
find / -type f -size +100M 2>/dev/null

Quote the pattern in -name "*.conf". Without quotes, the shell may expand the * itself before find ever sees it.

TestMatches
-name "*.log" / -inameFile name pattern (-iname ignores case)
-type fType: f file, d directory, l symlink, b block device, c character device, p named pipe, s socket
-size +10MBigger than 10 MiB. -size -1k smaller. Units: c bytes, k, M, G
-mtime -7Content modified less than 7 days ago (+7 more than 7, 7 exactly 7)
-atime, -ctimeSame, for access time and status-change time
-mmin -30Modified less than 30 minutes ago
-newer fileModified more recently than file
-user amin, -group devOwned by that user or group
-perm -4000Has these permission bits set (here: SUID)
-emptyEmpty file or directory
-maxdepth 1Don’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:

bash
find . -name "*.c" -o -name "*.h"
find . -type f ! -name "*.txt"
find . \( -name "*.tmp" -o -name "*.bak" \) -mtime +30
find 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:

ActionWhat it does
-lsPrint details like ls -l
-deleteDelete 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
bash
find logs -name "*.log" -exec wc -l {} +
find /tmp -type f -name "*.tmp" -mtime +7 -delete
text
1 logs/app2.log
1 logs/app3.log
1 logs/app1.log
3 total

The \; 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:

OptionMeaning
-cCreate an archive
-xExtract an archive
-tList the contents
-f fileThe archive file name (put it last in a group: -cvf name.tar)
-vVerbose: list files as they’re processed
-zCompress with gzip (.tar.gz, .tgz)
-jCompress with bzip2 (.tar.bz2)
-JCompress with xz (.tar.xz)
-C dirChange to this directory first (extract somewhere else)
--exclude=PATTERNLeave matching files out
bash
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/restore
text
project/
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.

bash
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
OptionMeaning
-oCopy-out mode: create an archive from a file list
-iCopy-in mode: extract from an archive
-pPass-through: copy files to another directory without an archive
-tList contents (with -i)
-dCreate leading directories when extracting
-vVerbose

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.

OperandMeaning
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=progressShow progress while copying
conv=Conversions, like ucase, notrunc or fsync
bash
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=fsync
text
10+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).

CompressDecompressExtensionSpeedSize
gzipgunzip (gzip -d).gzFastestBiggest
bzip2bunzip2 (bzip2 -d).bz2SlowSmaller
xzunxz (xz -d).xzSlowest to compressSmallest
bash
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*
text
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.xz

The options are almost the same for all three:

OptionMeaning
-kKeep the original file
-dDecompress
-cWrite to standard output, leave files alone (gzip -c f > f.gz)
-1 … -9Faster … smaller (default is -6 for gzip and xz, -9 for bzip2)
-lList compressed and original size (gzip and xz)
-tTest the compressed file’s integrity
-vVerbose

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/-R copies directories, cp -a also keeps owners, permissions and timestamps. mv needs no -r. rm -r deletes trees, rmdir only empty directories.
  • mkdir -p creates missing parents; rmdir -p removes empty parents. touch creates 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.
  • find tests: -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: c create, x extract, t list, f file, v verbose, z gzip, j bzip2, J xz, -C target directory.
  • cpio reads 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/xz replace the original (-k keeps it). Decompress with gunzip/bunzip2/unxz or -d. xz compresses smallest, gzip fastest.
  • file identifies a file by its contents, not its name.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. Which command finds regular files under /var/log changed in the last 2 days?
  2. You run gzip report.txt. What’s in the directory afterwards?
  3. Which tar command extracts an xz-compressed archive?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy