- Learn
- Computer Science & IT
- Information Technology
- Linux Basics
- Linux Processes, Packages and Services
Linux Processes, Packages and Services from the Command Line
ps, top and free, stop and reprioritize them with signals and nice, and inspect the hardware with tools such as lscpu, lsblk and lspci. Install, update and remove software with apt and dnf, manage services with systemctl, read logs with journalctl, /var/log and dmesg to troubleshoot a failing service, and back up files with tar, gzip, xz and zip.BeginnerLesson 6 of 7 in Linux Basics Course
What you will learn
- Find the programs running on a Linux system, watch how much CPU and memory they use, and stop, pause or reprioritize them safely.
- List processes and read what ps showsExplain what a process is, identify it by its process ID, and use
ps,pgrepand/procto find processes and read their state. - Watch CPU, memory and load with top, free and uptimeRead the live process view in
top, judge memory withfree, and decide from the load average whether a system is overloaded. - Stop processes with signalsSend signals with
kill,pkillandkillall, choose between a polite stop and a forced one, and check the result. - Run jobs in the background and set prioritiesMove commands between the foreground and the background, keep them running after logout, and change their CPU priority with
niceandrenice.
- List processes and read what ps shows
- Find out which processor, memory, disks and devices a Linux machine has, and which kernel and drivers it uses, without opening the case.
- Identify the processor, memory and systemUse
uname,lscpu,nproc,/procanddmidecodeto report the architecture, CPUs, memory and kernel of a machine. - List disks, PCI and USB devices and their driversName storage devices correctly, list the devices connected to a machine with
lsblk,lspciandlsusb, and find the drivers and kernel messages behind them.
- Identify the processor, memory and system
- Use the package managers of the Debian and Red Hat families to install, update, remove and inspect software safely from trusted repositories.
- Understand packages, repositories and dependenciesExplain what a package, a repository and a dependency are, how high-level and low-level package tools divide the work, and which tools each distribution family uses.
- Install, update and remove software with apt and dnfRefresh package information, install and upgrade software, and remove it cleanly with
apton Debian-family systems anddnfon Red Hat-family systems. - Search for packages and inspect installed softwareFind the package you need, check what is installed and at which version, see which files a package installed and which package owns a file, and review the package history.
- Understand packages, repositories and dependencies
- Check, start, stop, enable and customize background services with
systemctl, and understand how systemd decides what runs at boot.- Understand systemd, units and service statusExplain what a service and a systemd unit are, read the output of
systemctl status, and tell the difference between a service that is running and one that is enabled. - Start, stop, enable and disable servicesControl services with
systemctlnow and at boot, apply configuration changes safely, and choose the default boot target. - Read and customize unit filesFind and read the unit file behind a service, change its settings safely with drop-in overrides, and write a simple service of your own.
- Understand systemd, units and service status
- Find the messages that explain what a system and its services did, using the systemd journal, log files in
/var/logand the kernel's messages, and use them to fix a failing service.- Query the systemd journal with journalctlRead the systemd journal with
journalctl, filtered by service, boot, priority and time, and know where the journal is stored. - Read log files in /var/log and kernel messagesFind and read text log files in
/var/log, including rotated older files, and usedmesgto read the kernel's messages about hardware and drivers. - Troubleshoot a failing service step by stepCombine
systemctl,journalctland the program's own checks into a repeatable routine that finds why a service fails and confirms the fix.
- Query the systemd journal with journalctl
- Bundle files and directories into archives with
tarandzip, compress and decompress them with gzip, bzip2 and xz, and choose the right format for backups and sharing.- Create, list and extract tar archivesUse
tarto create compressed archives, check their contents and extract them into the right place without overwriting files by accident. - Compress files with gzip, bzip2, xz and zipCompress and decompress single files, read compressed logs without unpacking them, use
zipfor sharing, and choose a format by speed, size and purpose.
- Create, list and extract tar archives
Linux Processes, Packages and Services study guide
1Monitor and control running processes
A slow command, a busy server and a program that will not close all begin with the same question: what is running? Process tools let you connect a program name to its owner, process ID and resource use. You will read a snapshot, watch changes over time, then choose how to stop or pause work. Shell job control and CPU priorities give you more control over long tasks without losing the terminal prompt.
1.1 List processes and read what ps shows
A program such as /usr/bin/sleep is a file on disk. A process is a running instance of that program, with its own memory and resources. Three commands running the same program create three processes. Each live process has a PID, a process ID; Linux can reuse that number after it exits.
Find the process and its parent
A process is normally started by another process, its parent. The PPID column gives that parent's PID. Commands you start in a shell are its children. PID 1 is the first process started by the kernel; on a systemd system, it is systemd. pstree -p draws these family relationships when installed.
ps takes a snapshot. Its default selection is processes with your effective user ID on your current terminal. For a system-wide view, choose the columns you need:
| Command | Useful columns |
|---|---|
ps -ef | UID, PID, PPID, STIME, TIME, CMD |
ps aux | USER, PID, %CPU, %MEM, VSZ, RSS, TTY, STAT, START, TIME, COMMAND |
The BSD-style form ps aux has no dash. The USER field identifies the account whose permissions the process uses. A root process can access resources that a regular user's process cannot.
Read one line
Consider this example from ps aux:
www-data 2417 0.3 1.2 214560 48212 ? S 09:14 0:02 nginx: worker process
The owner is www-data, the PID is 2417, and CPU use has averaged 0.3% since startup. The process currently holds 1.2% of RAM. RSS is resident memory: 48,212 KiB, about 47.1 MiB. VSZ, 214,560 KiB, also includes virtual address space that is not resident in RAM. A large VSZ alone is not evidence of a memory shortage.
The ? means there is no controlling terminal. State S means sleeping, usually waiting for work. START is 09:14; TIME is two seconds of CPU work. TIME is not elapsed time: a server can run for days while using very little CPU.
Recognize process states
| State | Meaning |
|---|---|
R | Running or ready for CPU time |
S | Sleeping while waiting for an event |
D | Uninterruptible sleep, often a storage wait |
T | Stopped or paused |
Z | Zombie: exited, awaiting collection by its parent |
I | Idle kernel thread |
STAT may add flags: + for a foreground terminal group, s for a session leader, l for multiple threads, N for reduced CPU priority and < for raised priority. Sleeping is normal. A zombie is already dead and uses no CPU; sending it another termination signal cannot collect its exit status. A growing collection of zombies points to a parent program that needs attention.
Narrow the search
pgrep -a nginx shows matching PIDs and command lines. Patterns can match several names: pgrep ssh can find both sshd and ssh-agent. pgrep -u alice selects by owner; pidof nginx looks for a program name. A ps pipeline through grep can also show the grep process itself.
For the five largest memory users, run:
ps -eo pid,ppid,user,%mem,cmd --sort=-%mem | head -n 6
There are six lines because the first is a header. ps -p 2417 checks one PID. /proc/2417/status exposes its name, state, parent and memory details. /proc is a virtual view supplied by the kernel, not stored process reports on disk; the PID directory disappears when the process exits.
Key Takeaways
- A process is one running instance; its PID identifies it while it lives.
ps -efexposes parents;ps auxadds CPU and memory columns.- TIME measures CPU work, while START records when the process began.
- RSS measures resident RAM; VSZ includes other virtual memory.
- Sleeping processes are normal; zombies have already exited.
pgrepnarrows a search, and/proc/PID/statusexposes kernel information.
1.2 Watch CPU, memory and load with top, free and uptime
A snapshot tells you what exists; repeated observations show what is changing. top combines a live process list with totals for CPU activity, load, memory and swap. Read the summary and the busy processes together before deciding which resource is under pressure.
Work with top
Run top. Press P to sort by CPU, M to sort by memory, 1 to show each CPU, h for help and q to quit. Its k and r commands send signals and change nice values. htop offers another interactive view but may need installation.
The process columns include PID, USER, PR, NI, VIRT, RES, SHR, state, %CPU, %MEM, TIME+ and COMMAND. RES is resident RAM, like RSS in ps; VIRT includes reserved address space. In top's default per-CPU mode, a multithreaded process can reach 400% by keeping four CPUs busy. Pressing I switches the display to divide usage by the CPU count.
Identify the kind of CPU activity
The CPU summary splits time into categories:
| Field | What it reports |
|---|---|
us, sy | User-program work and kernel work |
ni | User work with adjusted nice priority |
id | Idle time |
wa | Idle time while I/O is outstanding |
hi, si | Hardware and software interrupt work |
st | Time a virtual machine lost to its host |
High user CPU use suggests computation. High wa with little user work directs attention toward storage waits. In a virtual machine, high st points to CPU time withheld by the host. These are different causes of a slow response.
Compare load with CPU capacity
uptime and top show load averages for the last 1, 5 and 15 minutes. Linux counts runnable tasks and tasks in uninterruptible sleep, including storage waits. Load is not a CPU percentage. nproc reports CPUs available to the current process, which is useful when interpreting capacity.
For CPU-bound work with little storage waiting, suppose nproc reports 4 and load is 6.00, 5.20, 3.10. The recent load is 1.5 tasks per CPU, so work has been queuing. The shorter-period value exceeds the longer-period value, showing a recent rise. On 16 CPUs, a load of 6 would be much lighter. A high load with idle CPUs can instead come from state-D tasks.
Judge memory with available
Run free -h. Its Mem row includes total, used, free, shared, buff/cache and available. Linux fills spare RAM with useful disk caches and can reclaim much of it. Free counts completely unused RAM; available estimates how much new work can use without swapping.
For example, a machine reports total 7.6Gi, used 3.1Gi, free 0.4Gi, buff/cache 4.6Gi and available 4.5Gi. The small free figure is not a shortage: about 59% remains available. In current procps versions, used is total minus available; free, used and cache are not a simple partition to add together.
The suffixes Ki, Mi and Gi are binary units. A GiB is 1,073,741,824 bytes; a GB is 1,000,000,000 bytes. free -m uses MiB and free -g whole GiB, which can hide small amounts through rounding.
Swap moves some memory contents to slower disk storage. Watch for low available memory together with growing swap use. If memory is exhausted, the kernel's out-of-memory killer can end a process. Check sudo journalctl -k for an OOM message before assuming an application crashed on its own.
Key Takeaways
- Use both the system summary and process list in
top. - Linux load counts runnable tasks and uninterruptible waits; it is not a percentage.
- Judge load against available CPUs and check for storage waiting.
- The available column is more useful than free for judging RAM headroom.
- Low available memory and growing swap use indicate pressure; OOM events appear in kernel logs.
1.3 Stop processes with signals
A signal is a short notification delivered to a process. It can request an exit, pause work or tell a service to reread settings. The kill command sends signals; its name does not mean that every signal kills the recipient.
Choose the signal
| Signal | Purpose |
|---|---|
SIGTERM | Request a clean exit; the default for kill |
SIGKILL | Force termination without application cleanup |
SIGINT | Interrupt the foreground program, usually with Ctrl+C |
SIGTSTP | Request a pause, usually with Ctrl+Z |
SIGSTOP | Force a pause |
SIGCONT | Continue a stopped process |
SIGHUP | Report terminal closure; some services use it to reload |
SIGQUIT | Quit, potentially with a core dump; Ctrl+\ sends it |
Most signals can be handled or ignored by the program. SIGKILL and SIGSTOP cannot be caught, blocked or ignored. kill -l lists names and numbers. Common x86 and ARM numbers include TERM 15, KILL 9, INT 2, HUP 1, QUIT 3, CONT 18, STOP 19 and TSTP 20. Names avoid architecture-dependent numbering.
Stop one process carefully
First establish what the process is. ps -p 5120 -o pid,user,stat,cmd lets you inspect the PID, owner, state and command. Then request a clean exit:
kill -TERM 5120
kill 5120, kill -15 5120 and kill -s TERM 5120 send the same request. A clean exit lets the application save work, close files and remove lock files. Give it time to respond, then run ps -p 5120 again. If only the header appears, it has exited.
If the same live process is still stuck after the wait, kill -KILL 5120 is the forced fallback. It loses the application's chance to clean up, so unsaved work and leftover temporary files may remain. Recheck the identity before escalating: PIDs can be reused after exit.
Match names before acting
pkill selects by a name pattern; killall selects a program name. Both normally send SIGTERM. Preview a broad pattern with pgrep -a fire before using pkill fire: that pattern can select more processes than the one you intended. pkill -u bob selects all of bob's processes, not a single application.
killall -HUP rsyslogd sends HUP to the matching logging processes. HUP's effect belongs to the application: check that it supports reloading before treating the signal as a reload command. For a systemd-managed service, use sudo systemctl stop NAME; the manager handles the service's process group and will not treat the requested stop as a failure to repair automatically.
Understand permissions and states
A regular account normally controls its own processes. An attempt to signal another account's process can produce "Operation not permitted"; sudo supplies root authority when needed. Verify the target before using that authority, because stopping the wrong service affects other users.
A process in state D can remain visible after SIGKILL while waiting for storage to respond. Repeating the signal does not repair that storage. A zombie in state Z has already exited; its parent must collect its exit status. Inspecting the state therefore matters when the process does not disappear.
Keyboard shortcuts target the foreground process group. Ctrl+C usually ends the work; Ctrl+Z pauses it and keeps its memory and open files. Terminal closure commonly leads to HUP and termination of attached jobs, which is why long tasks need deliberate handling.
Key Takeaways
- SIGTERM requests cleanup; SIGKILL forces exit without it.
- Preview pattern matches and verify the PID before sending a signal.
- SIGSTOP pauses and SIGCONT resumes;
killcan do more than terminate. - A zombie cannot be killed again, and storage waits can delay termination.
- Use
systemctl stopfor a managed service.
1.4 Run jobs in the background and set priorities
A foreground job occupies the terminal until it finishes or stops. A background job lets the shell accept another command while it runs. Job control changes where work runs; CPU priority changes how it competes with other work.
Move work between foreground and background
An ampersand starts a command in the background:
sleep 300 &
The shell might print [1] 6431. Here 1 is its local job number, and 6431 is the system-wide PID. jobs lists only this shell's jobs. fg %1 brings job 1 to the foreground. If you pause that foreground job with Ctrl+Z, bg %1 resumes it in the background. Without a number, fg and bg choose the job marked +.
Try the sequence with sleep 300: run it in the foreground, press Ctrl+Z, run bg, inspect jobs, then run fg and press Ctrl+C. "Stopped" means paused, not finished. A stopped job uses no CPU but still holds memory and open files. Bash may warn "There are stopped jobs" when you try to exit.
Keep output and logout under control
A background command can still print into the terminal. Redirect both output streams for a long task:
./report.sh > report.log 2>&1 &
The first redirection sends normal output to the file. 2>&1 sends error output to that same destination. The final & returns the prompt while the task runs.
Backgrounding alone does not protect a job from terminal closure. To start work that ignores SIGHUP, use:
nohup ./long-task.sh > task.log 2>&1 &
Without explicit output redirection, nohup commonly writes terminal-bound output to nohup.out. In Bash, disown %1 removes an existing job from the shell's job table, so Bash does not forward HUP to it. The program still needs usable input and output destinations. A program intended to run permanently is better managed as a service.
Give interactive work room to run
The nice value expresses CPU scheduling priority for ordinary processes. Values run from -20, highest priority, to 19, lowest priority; the usual starting value is 0. Higher values give competing work more opportunity. A nice-19 process can still use an otherwise idle CPU fully.
nice -n 10 xz -9 big.log
renice -n 15 -p 6431
The first command starts compression with a positive niceness adjustment; from the usual value 0 it becomes 10. The second changes the running process's nice value to 15. nice without -n applies an adjustment of 10. An ordinary user can generally raise their own process's nice value, reducing its CPU priority. Raising priority by lowering the value normally needs root, for example sudo renice -n -5 -p 6431.
In top, NI shows the nice value; for ordinary time-sharing processes PR is commonly 20 plus NI. Nice 10 therefore appears as PR 30. In ps aux, N marks reduced priority and < raised priority. Niceness affects CPU competition, not disk-access priority; ionice controls a separate resource.
Key Takeaways
&starts background work;jobs,fgandbguse shell-local job numbers.- Ctrl+Z pauses a job; it does not end it.
- Use output redirection and
nohupdeliberately for a long terminal task. - Higher nice values reduce CPU priority under contention, not maximum idle-CPU speed.
2Inspect hardware from the command line
Hardware information helps you choose a compatible package, interpret resource use and describe a fault clearly. Linux exposes the running kernel, CPU layout, usable memory and connected devices through command-line tools. You will distinguish logical CPUs from physical cores, decimal storage labels from binary sizes, and a detected device from one with a working driver. The same checks help when the hardware is virtual.
2.1 Identify the processor, memory and system
Before installing software or sizing a workload, find out what the system actually offers. The architecture determines which machine-code packages run. CPU availability helps explain load, and usable RAM limits the work that fits in memory.
Separate the kernel from the distribution
| Command | Information |
|---|---|
uname -r | Running kernel release, such as 6.8.0-45-generic |
uname -m | Architecture, such as x86_64 or aarch64 |
uname -a | All uname fields |
cat /etc/os-release | Distribution name and release |
hostnamectl | Host, OS, kernel and architecture summary |
Ubuntu 24.04 is a distribution release; a value such as 6.8.0-45-generic identifies the kernel running inside it. Installing a new kernel does not switch the running kernel immediately: that happens at reboot.
Architecture labels differ between package families. Debian packages use amd64 for the architecture reported by uname as x86_64, and arm64 for aarch64. RPM packages commonly use x86_64 and aarch64 directly. Match the build to the machine before installing it.
Count cores and logical CPUs
lscpu reports architecture, model, sockets, cores per socket, threads per core and logical CPUs. For a uniform CPU layout:
One socket with six cores and two threads per core gives 12 logical CPUs. There are still six physical cores. Two hardware threads share resources within a core, so 12 logical CPUs do not promise twice the performance of six cores.
nproc reports processing units available to the current process; CPU affinity or resource limits can make this smaller than the machine-wide count. /proc/cpuinfo provides CPU details directly. On x86, grep -c ^processor /proc/cpuinfo counts processor entries, and the vmx or svm flags show hardware virtualization support. ARM exposes different fields.
Read usable and installed memory
free -h gives a convenient RAM summary. /proc/meminfo provides details: MemTotal is usable RAM and MemAvailable estimates the capacity new work can use. This file labels its figures kB, but they are kibibytes, or 1,024 bytes each.
For example, MemTotal: 16303448 kB converts to about 15.5 GiB after division by 1,024 twice. A machine with 16 GiB of physical modules can show less usable RAM because firmware and kernel reservations use some of it.
To inspect installed modules and slots, run sudo dmidecode -t memory. sudo dmidecode -t system reports firmware-provided manufacturer, model and serial data. A virtual machine reports its virtual hardware. sudo lshw -short, when installed, provides a compact hardware inventory.
Check a requirement as separate tests
Suppose software needs a 64-bit ARM system, at least four available CPUs and 8 GB of RAM. uname -m returning aarch64 meets the architecture requirement. nproc returning 4 meets the CPU requirement. A total of 3.7Gi is only about 4.0 GB, so memory is insufficient. Passing two checks cannot compensate for failing the third.
Key Takeaways
- Use
/etc/os-releasefor the distribution anduname -rfor the running kernel. - Package architecture labels differ: Debian
amd64corresponds tox86_64. - Sockets, cores and hardware threads determine logical CPU count.
nprocreports CPUs available to the current process.- Usable RAM can be smaller than installed memory;
/proc/meminfouses binary kilobytes.
2.2 List disks, PCI and USB devices and their drivers
Linux gives hardware devices names under /dev and publishes its device view under /sys. Several listing tools answer different questions: which storage devices exist, which buses detected devices, and which drivers are handling them.
Identify disks and partitions
SATA, SAS and USB disks commonly appear as /dev/sda, /dev/sdb and later letters. Their partitions add a number, such as /dev/sda1. NVMe uses names such as /dev/nvme0n1, with /dev/nvme0n1p1 for a partition. A virtual machine may use /dev/vda.
lsblk shows block devices as a tree. TYPE distinguishes a disk from a partition; RM marks removability and RO marks read-only status. SIZE gives capacity and MOUNTPOINTS shows where a device is in use. Choose extra detail with:
lsblk -o NAME,SIZE,MODEL
lsblk -f
The first makes model and size easy to compare. The second adds file system type, label and UUID. Names such as sdb can change with detection order. Before writing to a disk, confirm its identity by more than the letter: writing to the wrong device destroys its data.
A drive sold as 512 GB contains 512 billion bytes. In GiB that is about 476.8, which lsblk displays as 476.8G. The device has not lost capacity: its label and the display use different units.
Find devices and bound drivers
| Tool | What to look for |
|---|---|
lspci | PCI and PCI Express devices, such as network and storage controllers |
lspci -k | The driver in use and possible kernel modules |
lsusb | USB device IDs and descriptions |
lsusb -t | USB connections as a tree, including speeds |
lsmod | Loaded kernel modules |
modinfo e1000e | Information about one module |
A USB ID such as 046d:c52b identifies the vendor and product more reliably than a broad name like "wireless receiver." In PCI output, distinguish Kernel modules, which names possible modules, from Kernel driver in use, which identifies a bound driver. Detection alone is not the same as working support.
Most drivers can be loaded as kernel modules, pieces of kernel code added when needed. Loading or removing modules changes the running kernel and requires root authority. Some drivers are built into the kernel instead. On ARM boards, many built-in devices do not sit on PCI, so a short lspci listing need not mean hardware is missing.
Follow a connection in the kernel log
When a USB disk is plugged in, run sudo dmesg | tail, or start sudo dmesg -w before connecting it. A message such as [sdb] 60437492 512-byte logical blocks identifies the new disk as /dev/sdb and gives its capacity. Multiplying those block counts gives 30,943,995,904 bytes: about 30.9 GB or 28.8 GiB.
Then compare the new lsblk entry with that message and the device model. If a detected adapter fails to work, use lspci -k to check the driver and dmesg to read initialization errors. A missing driver binding and a driver that reports an error require different follow-up checks.
Key Takeaways
- Use
lsblkfor block devices,lspcifor PCI andlsusbfor USB. - Disk names follow detection order; verify the device before writing.
- A decimal 512 GB drive is about 476.8 GiB.
- Check the bound driver and kernel messages after detecting a device.
3Install and manage software with package managers
A package manager connects software files with their versions, dependencies and trusted sources. Choosing the right tool for the distribution lets you install and maintain software without tracking every library yourself. You will learn the Debian and Red Hat command families, separate refreshing package information from applying upgrades, and trace an installed command back to the package and transaction that supplied it.
3.1 Understand packages, repositories and dependencies
A package bundles software files with information used to install and maintain them. Its metadata names the version, architecture and required packages, and it can include installation scripts. A package manager records which files belong to which installed package.
Match the distribution family
| Systems | Package format | Repository tool | Low-level tool |
|---|---|---|---|
| Debian, Ubuntu, Linux Mint | .deb | apt | dpkg |
| Fedora, RHEL, Rocky Linux, AlmaLinux, CentOS Stream | .rpm | dnf | rpm |
| openSUSE, SUSE Linux Enterprise | .rpm | zypper | rpm |
Arch Linux uses pacman; Alpine Linux uses apk. The older yum name belongs to the Red Hat family. If you are unsure which system you have, read cat /etc/os-release before choosing commands.
A file such as nginx_1.24.0-2_amd64.deb names nginx, its software version, packaging revision and architecture. These fields help the package manager select a compatible build. A familiar application name does not make every downloaded package suitable for every distribution.
Let the high-level tool resolve dependencies
A dependency is another package needed by the software, often a shared library. Installing one application may therefore add several packages. A high-level tool such as apt or dnf finds a compatible set, downloads it and asks the lower-level tool to install it.
dpkg and rpm work with local package files and maintain the installed-package database. They do not fetch missing dependencies from repositories. Using them to install a file can leave missing requirements for you to resolve. High-level tools can install local files too, while resolving their requirements from configured repositories.
Searching and querying work as a regular user. Installation, removal and upgrades change system files and normally need sudo. The confirmation screen is useful information: inspect the additional packages and any proposed removals before accepting.
Understand repository trust
A repository provides package files and indexes describing the available versions and dependencies. A distribution's own repositories offer a set built for its release.
APT verifies signed repository metadata and follows package checksums from that metadata to the downloaded files. It does not normally check a separate signature on each .deb. DNF normally verifies distribution RPM signatures; repository-metadata signature checking is configured separately. These checks establish a chain to a trusted publisher and help detect tampering.
Adding a third-party repository also adds trust in that publisher's software and installation scripts. Obtain its signing key through the publisher's genuine instructions. Do not bypass signature checks to get past an error such as "NO_PUBKEY". A file from an unknown download page also needs a trustworthy origin; the package extension alone supplies no such trust.
Search by the right name
Software and package names can differ. Apache is packaged as apache2 on Debian-family systems and httpd on Red Hat-family systems. The dig command comes from bind9-dnsutils or bind-utils. Search before assuming that a command name is also its package name.
Other installation systems keep separate records. Snap, Flatpak and AppImage bundle applications with many dependencies; pip and npm manage programming libraries. Installing a Python library with pip does not make it an apt-managed package.
Key Takeaways
- Use the package family and repository tool that match
/etc/os-release. - High-level tools fetch dependencies;
dpkgandrpmoperate on local packages and records. - Repositories provide package indexes and a trust chain to a publisher.
- Package names can differ from program names and between distributions.
- System package managers and application or language managers keep separate records.
3.2 Install, update and remove software with apt and dnf
Package maintenance has three separate jobs: learn what is available, apply selected changes and remove software that is no longer needed. Read the planned transaction before confirming, especially when it removes packages.
Refresh and upgrade
| Task | Debian family | Red Hat family |
|---|---|---|
| Refresh package lists | sudo apt update | DNF refreshes stale metadata automatically |
| Apply upgrades | sudo apt upgrade | sudo dnf upgrade |
| Install nginx | sudo apt install nginx | sudo dnf install nginx |
| Remove nginx | sudo apt remove nginx | sudo dnf remove nginx |
| Remove unneeded dependencies | sudo apt autoremove | sudo dnf autoremove |
apt update does not upgrade software. It downloads current package lists. Follow it with sudo apt upgrade to install newer versions. DNF's upgrade command handles stale repository metadata as part of its work. DNF4 uses dnf check-update to list available changes; DNF5 uses dnf check-upgrade.
apt upgrade will not remove an installed package to complete an upgrade. A package needing such a change may be held back. sudo apt full-upgrade permits removals, so inspect its plan carefully. -y accepts a transaction automatically and removes your opportunity to review it interactively.
Install from a repository or a local file
On Ubuntu, run sudo apt update, then sudo apt install htop. APT lists new packages and dependencies before downloading them. htop --version checks the installed program. On Fedora, use sudo dnf install htop.
Running apt install for an existing package can upgrade it to the current candidate; it changes nothing if that version is already installed. To install a trusted local file, name its path:
sudo apt install ./app_2.1.0_amd64.deb
sudo dnf install ./app-2.1.0-1.x86_64.rpm
The ./ marks a file path. In contrast, sudo dpkg -i file.deb and sudo rpm -i file.rpm do not fetch missing dependencies. If dpkg leaves dependencies unsatisfied, sudo apt --fix-broken install can resolve them; inspect the proposed repair.
Remove software and settings deliberately
APT's remove retains the package's managed system configuration; purge removes that too. Neither removes files from users' home directories. Autoremove targets automatically installed dependencies no longer needed by installed packages. It is a different decision from removing one application by name.
APT source entries live in /etc/apt/sources.list and /etc/apt/sources.list.d/; Ubuntu 24.04 commonly uses ubuntu.sources in that directory. Refresh after changing sources. DNF reads .repo files under /etc/yum.repos.d/; dnf repolist shows enabled repositories.
Finish maintenance cleanly
apt is designed for interactive use. Scripts generally use the more stable interfaces of apt-get and apt-cache. Their commands cover the same broad tasks, although defaults can differ.
A newly installed kernel becomes the running kernel after reboot. Programs using replaced libraries need restarting to load the new code. Ubuntu can indicate a needed reboot with /var/run/reboot-required.
A package lock often means an automatic update or another package operation is active. Wait for it to finish; deleting the lock file can damage package records. A permission error instead points to missing authority, so confirm whether the operation needs sudo.
Key Takeaways
apt updaterefreshes lists;apt upgradechanges installed software.- DNF refreshes stale metadata during upgrade; DNF4 and DNF5 name the update check differently.
- APT remove retains managed system configuration; purge removes it.
- Use a path with apt or dnf to install a local file and resolve dependencies.
- Review removals in a full upgrade and dependencies proposed for autoremove.
- Wait for a package lock holder and restart or reboot when updated code requires it.
3.3 Search for packages and inspect installed software
When a command is missing or a version changes, package queries let you work backward from the symptom. Start by deciding whether you need repository information, installed-package information or the owner of a particular file.
Search before installing
apt search json and dnf search json look through package names and descriptions. Inspect a promising result with apt show NAME or dnf info NAME. These show details such as version, size, description and repository. APT's show output also lists dependencies; DNF requirements can be queried with dnf repoquery --requires NAME.
Repository information answers what you could install. It does not alone establish what is already installed. apt policy NAME distinguishes the installed version from the candidate, the version APT would currently select. apt list --upgradeable or dnf list --upgrades shows installed packages with available updates.
Query installed records
| Question | Debian family | Red Hat family |
|---|---|---|
| What is installed? | apt list --installed or dpkg -l | dnf list --installed or rpm -qa |
| What version of one package is installed? | dpkg -l nginx | rpm -q nginx |
| Which files came from htop? | dpkg -L htop | rpm -ql htop |
| Who owns this installed file? | dpkg -S /usr/bin/htop | rpm -qf /usr/bin/htop |
In dpkg -l, the status ii identifies an installed package. The direction of a query matters: -L starts with a package and lists its files; -S starts with a file and finds its owner. On RPM systems, the parallel distinction is -ql versus -qf.
Trace a command to its package
Suppose which openssl prints /usr/bin/openssl. On Debian, dpkg -S /usr/bin/openssl identifies the owning package as openssl. apt policy openssl then shows the installed version, candidate and repositories. This avoids assuming the command's name must always match its package.
For a missing command, there may be no installed owner to query. dnf provides /usr/bin/rsync searches repository file lists. Debian-family systems offer the separate apt-file tool: after its index is refreshed with sudo apt-file update, apt-file search bin/rsync finds providers. Ubuntu may also suggest a package when a command is not found.
Connect a fault with a transaction
APT records transactions in /var/log/apt/history.log; dpkg records lower-level actions in /var/log/dpkg.log. On DNF4, dnf history lists transactions; DNF5 uses dnf history list. dnf history info 12 shows the packages changed in transaction 12.
sudo dnf history undo 12 requests reversal of that transaction. Review its plan: reversal depends on the needed package versions still being available and does not restore arbitrary application data. For diagnosis, read the history before making another change. A recent library upgrade may explain why a program's behavior changed even though nobody reinstalled the main application.
Key Takeaways
- Distinguish repository versions from the version actually installed.
- Use
dpkg -Lorrpm -qlfor package-to-files queries. - Use
dpkg -Sorrpm -qffor installed-file-to-package queries. - A missing file needs a repository provider search, not an installed-owner query.
- Transaction history helps connect a new problem with a recent package change.
4Manage services with systemd
Services keep doing useful work after a user leaves the terminal. systemd manages their startup, current state and response to failure, using unit files to describe what should run. You will read status without confusing it with boot configuration, control services now and on future boots, and make small configuration changes that survive package updates. A simple service file shows how these settings fit together.
4.1 Understand systemd, units and service status
A service, often called a daemon, provides a background function such as serving web pages or accepting SSH connections. It usually has no terminal. Many daemon names end in d, as in sshd and chronyd.
Find the service manager
On most mainstream distributions, systemd runs as PID 1 and starts services in the required order. Check with ps -p 1 -o comm=. systemd can supervise processes, restart failed services and arrange their log collection. Some distributions use another manager, such as Alpine Linux's OpenRC.
systemd manages units. Their suffixes identify their roles:
| Suffix | Role |
|---|---|
.service | Run and manage a program or task |
.socket | Listen on a socket and activate a service when needed |
.timer | Schedule activation |
.mount | Represent a mounted file system |
.target | Group units into a named system state |
In service commands, nginx is shorthand for nginx.service. Names vary: SSH commonly uses ssh on Debian and Ubuntu, and sshd on Fedora and RHEL. Apache is apache2 or httpd. systemctl list-unit-files | grep ssh helps find the local name.
Read the two important status lines
Run systemctl status nginx. An example can include:
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
Active: active (running) since Wed 2026-10-21 09:14:03 UTC
Main PID: 2410 (nginx)
Loaded names the unit file and its enablement state. Active reports the current state and when it began. Main PID identifies the principal process; recent log lines follow. A regular user can inspect status, but system log visibility can require additional privileges.
Active and enabled are independent. Active describes the present. Enabled means enablement links have been created, commonly so a target starts the service at boot. A disabled service can still be started manually or activated by another unit. An enabled service can be stopped or failed.
Interpret the state accurately
| Active state | Interpretation |
|---|---|
active (running) | The service's program is running |
active (exited) | A completed task is still considered active |
inactive (dead) | It is not active |
failed | A start or run failed; examine the result and logs |
activating | Startup is in progress |
The color of the status dot helps scanning, but the state text is the useful evidence. systemctl is-active nginx reports the current state; systemctl is-enabled nginx reports enablement. static means the unit has no enablement instructions and can be activated through another route. masked means starting it is blocked.
Choose the right overview
systemctl list-units --type=service shows service units currently loaded, with its default state filtering. Add --all to include inactive loaded units, or --state=running to focus on running services. systemctl --failed isolates failed units. systemctl list-unit-files --type=service lists installed service files and enablement states, including services that are not running now.
Key Takeaways
- systemd manages units; a
.serviceunit describes a program or task. - Read Loaded for the unit file and enablement, and Active for the present state.
- An enabled service can be stopped; a disabled service can be running.
active (exited)can describe a successful completed task.- Use list-unit-files for installed definitions and list-units for loaded units.
4.2 Start, stop, enable and disable services
Service control has two time scales: what should run now, and what should be started automatically later. Keep those decisions separate when installing software or repairing a service.
Control the current state
| Command | Effect |
|---|---|
sudo systemctl start nginx | Start now |
sudo systemctl stop nginx | Stop now |
sudo systemctl restart nginx | Stop and start, interrupting current work |
sudo systemctl reload nginx | Ask a supporting service to reread configuration |
sudo systemctl reload-or-restart nginx | Reload if supported; otherwise restart |
Use systemctl status nginx after a change. For a quiet check, systemctl is-active --quiet nginx returns success when it is active. It prints no state text, making it useful in shell conditions.
Reload support comes from the service. For nginx, test a changed configuration with sudo nginx -t before sudo systemctl reload nginx. A successful reload can apply new settings without stopping the service. With a broken configuration, nginx retains the old running configuration on reload; restarting with the broken file can instead leave it down.
Configure automatic startup
sudo systemctl enable nginx creates enablement links; it does not start nginx now. sudo systemctl disable nginx removes those links; it does not stop the current process. To make both changes together:
sudo systemctl enable --now nginx
sudo systemctl disable --now nginx
The first enables and starts; the second disables and stops. A Fedora installation of nginx commonly leaves it stopped and disabled, while Debian-family package installation often starts and enables it. Check the actual state after installation.
After starting a web service, curl -I http://localhost can check its local response. A local success and access from another machine are different tests; a firewall can still block remote access.
Block activation when necessary
Disabling does not prevent a dependency or socket from activating a service. Masking blocks startup by linking the unit name to /dev/null:
sudo systemctl mask bluetooth
sudo systemctl unmask bluetooth
Masking alone does not stop an already running unit. Stop it as well when it must cease running. Unmasking removes the block; it does not by itself start or enable the service. A masked unit's start attempt reports that it is masked.
Choose the default system state
A target groups units. multi-user.target provides the normal non-graphical multi-user environment, commonly used on servers. graphical.target adds the desktop. systemctl get-default reports the default target, and sudo systemctl set-default multi-user.target changes the target selected for future boots; it does not immediately close the current desktop.
sudo systemctl reboot restarts the machine and sudo systemctl poweroff shuts it down. For a single service, use its own control commands instead. Killing a managed service's PID can trigger an automatic restart; an intentional systemctl stop tells systemd to keep it stopped.
Key Takeaways
- Start and stop affect the present; enable and disable change enablement links.
enable --nowanddisable --nowcombine both time scales.- Disabling allows other activation paths; masking blocks startup.
- Masking alone leaves an already running service running.
- Test application configuration before reloading or restarting.
- Changing the default target selects future boot behavior.
4.3 Read and customize unit files
A unit file tells systemd how to run a service. Read the effective configuration with systemctl cat NAME: it prints the base file and any overrides with their paths.
Know where settings belong
Packaged units live under /usr/lib/systemd/system/, also reached as /lib/systemd/system/ on Debian-family systems. Local administrator files and overrides belong under /etc/systemd/system/, which has precedence. A package update can replace its own file, so keep local changes in an override.
A unit file has sections and Key=value settings:
| Section | Important settings |
|---|---|
[Unit] | Description=, ordering with After=, dependencies with Wants= or Requires= |
[Service] | ExecStart=, User=, WorkingDirectory=, Environment=, Restart= |
[Install] | WantedBy=, used when enabling the unit |
After=network.target sets ordering; it does not itself start that target or promise Internet connectivity. WantedBy=multi-user.target tells enable to create a link under multi-user.target.wants/. A static unit has no enablement instructions but can still be activated by another unit.
Build a simple service
For a small test server, first prepare /srv/hello with readable files and a system account:
sudo useradd --system --no-create-home hello
With Python 3 installed at /usr/bin/python3, write /etc/systemd/system/hello-web.service:
[Unit]
Description=Hello web server
After=network.target
[Service]
ExecStart=/usr/bin/python3 -m http.server 8080 --directory /srv/hello
User=hello
Restart=on-failure
[Install]
WantedBy=multi-user.target
Run sudo systemctl daemon-reload, then sudo systemctl enable --now hello-web. Inspect systemctl status hello-web and request http://localhost:8080 with curl. The service account needs permission to read the directory and traverse its parent directories.
With the default Type=simple, the program stays in the foreground so systemd can track it. ExecStart= accepts an absolute executable path or a simple filename from systemd's search path. A relative path with a slash, such as ./server, is invalid. A program that forks into the background needs an appropriate service type such as Type=forking.
Override a packaged setting
sudo systemctl edit nginx opens a drop-in. For example:
[Service]
Restart=on-failure
RestartSec=5s
Saving through systemctl edit reloads systemd's unit configuration. Restart the service to apply changed runtime settings. When editing files directly, run sudo systemctl daemon-reload yourself before restarting. This reloads unit definitions, not the application's own configuration.
Replacing a list setting such as ExecStart requires an empty ExecStart= line before the new one. sudo systemctl revert nginx removes local overrides and restores the vendor configuration.
Restart=no leaves a finished process stopped. on-failure restarts after qualifying failures; always also covers clean exits. An intentional systemctl stop suppresses automatic restart. Rapid failures can hit a configured start-rate limit. The manager defaults allow five starts in 10 seconds; local configuration can change them. Fix the cause before clearing the failed state and trying again.
Key Takeaways
- Keep local settings under
/etc/systemd/system/; inspect them withsystemctl cat. - Unit sections separate description and dependencies, execution, and enablement.
- Run a simple service in the foreground under an appropriate account.
- Reload unit definitions after direct edits, then restart to apply runtime changes.
- A drop-in survives package updates; list settings may need an empty reset line.
- Restart policy handles process exits, while rate limits prevent endless rapid attempts.
5Read system logs to troubleshoot problems
A service state tells you that something failed; logs help explain why. Linux records messages in the systemd journal, application log files and the kernel message buffer. You will narrow those records by service, boot, time and severity, then connect the first useful error to a specific check. A disciplined repair changes one cause at a time and verifies both the running service and its intended startup behavior.
5.1 Query the systemd journal with journalctl
The systemd journal collects kernel, boot and service messages, including output sent to the journal by managed programs. systemd-journald stores indexed binary records. Read them with journalctl; a text-file reader such as less cannot interpret the journal files themselves.
Read enough of the record
System-journal access depends on permissions and local policy. Root and authorized groups such as systemd-journal or adm can read system entries. If a regular account sees only a limited set, use sudo journalctl for the system investigation.
The default view starts with old messages in a pager. Use arrow keys to move, / to search and q to quit. Choose a more focused view:
| Option | Effect |
|---|---|
-r | Newest first |
-e | Jump to the end |
-n 50 | Last 50 records |
-f | Follow arriving records until Ctrl+C |
--no-pager | Print directly, useful for pipes |
-n without a number selects ten entries. Status output often shows only a few recent lines, so read the journal when those lines do not explain the failure.
Combine unit, boot and time filters
sudo journalctl -u nginx -b selects nginx records from this boot. -b -1 selects the previous boot; --list-boots lists retained boot records. -k selects kernel messages and normally implies the current boot. For older kernel records, give the boot explicitly.
Time filters accept relative times and full dates:
sudo journalctl -u nginx --since "2026-10-22 08:00" --until "2026-10-22 09:30"
--since today means since midnight today, while --since "1 hour ago" gives a moving time window. Quoted date-time strings stay together as one argument. A date without a time starts at midnight.
Understand the priority cutoff
Priorities run from 0, emergency, to 7, debug. In between are alert, critical, error, warning, notice and information. Lower numbers are more severe. -p err includes levels 0 through 3, not just error. Use an explicit range such as -p err..warning to select that band.
A narrow severity filter can hide the evidence you need. For example, SSH can record failed-password messages at information level. On Ubuntu, sudo journalctl -u ssh --since today --grep "Failed password" finds matching messages without dropping them through a warning cutoff.
A line such as "Failed password for invalid user admin from 203.0.113.45" identifies the attempted account and source address. The timestamp and program PID place it in the surrounding activity. -o short-iso makes full dates easy to compare; -o verbose exposes fields, -o json-pretty prints structured records and -x adds available explanatory text.
Know what survives a reboot
Persistent journals live under /var/log/journal/; volatile journals under /run/log/journal/ disappear at shutdown. Storage behavior is controlled by Storage= in journald configuration. One recorded boot can mean older records were never persisted or have already been removed.
journalctl --disk-usage includes active and archived journal files. sudo journalctl --vacuum-size=500M removes old archived files toward a 500 MiB archived-file limit. Active files are not removed by that operation, so the total disk-usage report can remain larger.
Key Takeaways
- Filter by unit, boot and time before narrowing priority.
- A priority cutoff includes more severe levels, not only the named level.
- Information-level records can contain the cause of a problem.
- Persistent journals survive reboot; volatile journals do not.
- Vacuuming removes archived files, while disk usage also counts active files.
5.2 Read log files in /var/log and kernel messages
The journal is not the only log source. Some systems also run rsyslog, and applications can write their own text logs. The kernel keeps a separate in-memory message buffer. Choose the source that recorded the event you are investigating.
Find the right text log
| Source | Common location |
|---|---|
| Debian/Ubuntu general messages, with syslog configured | /var/log/syslog |
| Debian/Ubuntu authentication | /var/log/auth.log |
| Debian/Ubuntu kernel text log | /var/log/kern.log |
| RHEL-family general messages and authentication | /var/log/messages, /var/log/secure |
| APT and dpkg actions | /var/log/apt/history.log, /var/log/dpkg.log |
| DNF actions | /var/log/dnf.log |
| nginx requests and problems | /var/log/nginx/access.log, /var/log/nginx/error.log |
A file's presence depends on installed logging services and their configuration. Debian 12 and later commonly rely on the journal unless rsyslog is installed. Applications may still keep their own logs on such a machine.
Read a text file with sudo less /var/log/auth.log, inspect its end with sudo tail -n 20 /var/log/syslog, or follow arrivals with sudo tail -f /var/log/nginx/error.log. To select a word in any capitalization, use sudo grep -i "error" /var/log/syslog.
Read the fields and older files
A classic example is:
Oct 22 08:01:17 web1 sshd[3141]: Accepted publickey for alice from 198.51.100.7 port 50522 ssh2
It gives the time, host, program with PID, and event message. Some systems use full ISO timestamps with time-zone offsets instead. The message describes a successful key login, not a failed password attempt; reading only the program name loses that distinction.
Log rotation limits growth by renaming old files, creating new ones and eventually removing expired files. logrotate configuration lives in /etc/logrotate.conf and /etc/logrotate.d/. A sequence such as syslog, syslog.1 and syslog.2.gz spans current and older records. Use zless or zgrep for gzip-compressed text without extracting it first. A search of the current file alone can miss yesterday's fault.
Read kernel events
The kernel's ring buffer holds recent messages and overwrites its oldest entries as it fills. It records device detection, driver failures, storage errors and out-of-memory kills. dmesg prints it; use sudo when access is restricted. dmesg -T gives readable times, dmesg -l err,warn selects errors and warnings, and dmesg -w follows new messages.
sudo journalctl -k reads kernel entries retained by the journal. sudo journalctl -k -b -1 can reach a previous boot that the live ring buffer no longer holds.
If a Java process disappears, a kernel line such as "Out of memory: Killed process 4810 (java)" connects its exit to memory pressure. Check free -h and top, then reduce the memory demand or add capacity. For service startup problems, begin with the unit journal; for application-specific details, read its own error log.
Use rotation or journal retention controls to manage log space. Deleting a text log by hand removes evidence and may leave its disk space allocated until the writer closes the file.
Key Takeaways
- Text-log locations depend on the logging setup; applications may keep their own files.
- Use less, tail and grep for text logs, and zless or zgrep for compressed older logs.
- Rotation spreads an event history across several files.
- dmesg shows the current kernel buffer; the journal may retain earlier boots.
- Kernel OOM messages can explain an application that vanished without its own error.
5.3 Troubleshoot a failing service step by step
Repeated restarts rarely explain a failure. Start with the visible symptom, collect the message that names its cause and change one thing. Then test the repaired service through both its manager and the function it provides.
Follow a repeatable investigation
- Confirm the symptom: for example, a local web request fails.
- Run
systemctl status NAMEand read Active, Result and the exit code. - Read
sudo journalctl -u NAME -b, or the last 50 entries with-n 50 --no-pager. - Use the application's own error log and configuration test.
- Correct one identified cause and repeat the relevant check.
- Start or restart, inspect status and test the actual function.
- Check
systemctl is-enabled NAMEagainst the intended boot behavior.
Read the first meaningful error in the failed attempt. A later "Failed to start" line summarizes the result; it may not name the cause. Keeping the time and unit filters aligned helps separate the latest attempt from older failures.
Work through a port conflict
An nginx restart fails. Its journal contains "bind() to 0.0.0.0:80 failed (98: Address already in use)." Something is already listening on that port. Run:
sudo ss -tlnp | grep ':80 '
Suppose it identifies apache2. If this machine is intended to use nginx and Apache is no longer required, sudo systemctl disable --now apache2 stops Apache and removes its enablement links. Then sudo systemctl start nginx can acquire the port. Check systemctl status nginx and a local web request.
The condition matters: do not remove a needed service merely to make a second one start. If both must run, their listening configuration needs a deliberate change. The log identifies the resource conflict, while the system's intended role determines the repair.
Work through a configuration error
Suppose the journal reports an unexpected closing brace in /etc/nginx/sites-enabled/default:24. Run sudo nginx -t; it identifies the same file and line. Correct the misplaced brace, run the test again, and restart only after the test succeeds. This isolates the change and avoids replacing a known running configuration with a broken one.
Use the result code to narrow the search
| Status or result | Next check |
|---|---|
203/EXEC | Executable path, execute permission and ability to launch it |
217/USER | Account in User= and ability to establish its credentials |
1/FAILURE | Application's own error messages |
oom-kill | Kernel OOM records and memory use |
A missing executable and a program that starts but rejects its settings are different failures. For "Permission denied," compare ls -l output and directory access with the service's configured user. For a full disk check df -h; for low RAM check free -h; for CPU pressure inspect top.
If systemd reports "start request repeated too quickly," first repair the cause. Then sudo systemctl reset-failed NAME clears the failure and start-limit counters so you can start it again. Resetting the counter alone does not repair the program.
Key Takeaways
- Confirm the symptom, inspect status and read the first causal error.
- Use application checks and change one cause at a time.
- A busy port needs identification of the current listener before repair.
- Exit codes separate execution, user-credential, application and memory failures.
- Clear a start limit after fixing the cause, then verify status, function and boot intent.
6Archive and compress files
An archive collects files into one object; compression changes how much space that object uses. Keeping these jobs distinct makes backup commands easier to read and restore. You will build and inspect tar archives, extract into a chosen directory, and compare gzip, bzip2, xz and zip. Format choice depends on speed, size, sharing needs and file metadata, while a checked restore gives stronger evidence than a familiar filename.
6.1 Create, list and extract tar archives
An archive bundles files and directories with their names and metadata. Compression reduces the bytes needed to store data. A plain tar archive bundles files without compressing them; adding a compressor produces files such as .tar.gz, .tar.bz2 or .tar.xz.
Read the options as a small sentence
| Option | Job |
|---|---|
-c, -t, -x | Create, list or extract; choose one operation |
-f FILE | Name the archive file |
-v | Show member names or details |
-z, -j, -J | Use gzip, bzip2 or xz |
-C DIR | Change directory for following members or extraction |
GNU tar also accepts combined options and the older no-dash style. With a combined group, keep f last and put its filename next. The uppercase J selects xz; lowercase j selects bzip2.
Create an archive with useful member names
tar -czvf site-backup.tar.gz -C /var/www site
This creates site-backup.tar.gz in the shell's current directory. Tar changes its input location to /var/www, then adds site, so stored names begin site/. It preserves directory structure, modes, ownership metadata and timestamps.
Giving /var/www/site directly also works. GNU tar normally strips the leading slash and stores var/www/site/...; extraction then rebuilds that path beneath the destination. Choosing the input directory with -C gives a shorter, more convenient restore layout.
List before restoring
Run tar -tzvf site-backup.tar.gz. It lists names and metadata without extracting. Check whether all members sit beneath one directory. If not, extracting can scatter files across the destination. GNU tar detects common compression formats when reading, so tar -tvf site-backup.tar.gz also works.
To restore into an existing empty directory:
tar -xzvf site-backup.tar.gz -C /tmp/restore
The destination must already exist. Extraction can overwrite files with matching names, so use an empty restore directory when checking an unfamiliar archive. To extract one member, name it exactly as listed: tar -xzvf site-backup.tar.gz site/index.html.
Protect the archive filename and metadata
The word after -f is the archive filename. In tar -cfz backup.tar.gz docs, tar treats z as that filename and the later words as inputs. Similarly, tar -cf *.txt lets shell expansion choose the first text file as the output archive and can overwrite it. Always name the archive explicitly.
A regular user restores files under their own ownership; root can restore recorded owners. Creating a backup requires read access to the source. For protected system files, use an authorized command such as sudo tar -czf /root/etc-2026-10-22.tar.gz /etc, and check its errors for omitted files.
--exclude='*.log' omits matching paths. GNU tar's -a selects a compressor from the suffix, as in tar -caf backup.tar.xz docs. Before removing originals, read the archive with tar -tzf backup.tar.gz > /dev/null and confirm that the listing contains the expected files. A successful read checks readability; inspecting a restore also checks that the chosen contents are useful.
Key Takeaways
- Archiving collects files and metadata; compression reduces size.
- Choose one tar operation and give
-fan explicit archive filename. -Ccontrols input layout or the extraction destination.- List before extracting and restore into an empty directory to avoid overwrites.
- Backups need read permission, and root can restore recorded ownership.
- Check readable contents and a restore before relying on the archive.
6.2 Compress files with gzip, bzip2, xz and zip
Compression tools differ in speed, size and how they handle originals. Choose a format based on the job: a quick log reduction, a Linux backup or a download for users on several operating systems.
Compress a file and keep the original when needed
| Compressor | Compressed suffix | Decompress command |
|---|---|---|
gzip | .gz | gunzip or gzip -d |
bzip2 | .bz2 | bunzip2 or bzip2 -d |
xz | .xz | unxz or xz -d |
These tools normally replace an input file with its compressed version. gzip access.log leaves access.log.gz and removes the original after success. Add -k to keep it. Their -d forms reverse the operation.
They do not build a multi-file directory archive. gzip project refuses a directory; recursive gzip compresses its files individually. To preserve a directory tree as one compressed object, create a tar archive with the chosen compressor.
Balance time, memory and size
Gzip is usually fast, xz often makes smaller files at a greater time and memory cost, and bzip2 commonly lies between them. Results depend on the input and settings. Levels from -1 to -9 favor speed at the low end and compression at the high end. Defaults are 6 for gzip and xz and 9 for bzip2.
Text logs often shrink greatly. JPEG images, MP4 video and compressed archives usually gain little from another pass. Recompressing them can spend CPU time without a useful space saving.
For one sample of 240 MiB of logs, gzip produced 31 MiB and xz 22 MiB. Those outputs retain about 12.9% and 9.2% of the original size. The smaller file comes with a longer compression run in that sample; the figures are not predictions for other data.
Read and test compressed content
zcat, zless and zgrep read gzip-compressed text; bzcat and xzcat handle their respective formats. For example, zgrep "error" /var/log/syslog.2.gz searches a rotated log without leaving an uncompressed copy on disk.
Use gzip -t file.gz or xz -t file.xz for integrity checks. A suffix is only a naming convention: file backup.bin can identify gzip content even without .gz. sha256sum backup.tar.gz produces a checksum for comparison after transfer. Matching checksums show that the copies match, not that every wanted source file was included.
Share a directory with zip
ZIP bundles and compresses while keeping the source files:
zip -r project.zip project
unzip -l project.zip
unzip project.zip -d /tmp/project
-r includes the directory's contents recursively. unzip -l lists them; -d chooses the extraction destination. The commands may need installation first. ZIP is convenient for Windows and macOS users. Linux ZIP tools can store Unix metadata, but restoring ownership and modes across other systems is less portable than using tar for a Linux backup.
Choose .tar.gz for a routine Linux backup, .tar.xz when reducing a download matters more than compression time, .zip for broad desktop sharing and gzip for one large text file. Keep source files until checks and a trial restore establish that the archive contains what you need.
Key Takeaways
- Gzip, bzip2 and xz compress individual files and normally replace their inputs.
- Use
-kto keep an original; use tar to bundle a directory. - Compression gains and resource costs depend on input and settings.
- Use compressed-text readers and integrity tests without extracting everything.
- ZIP is convenient for sharing; tar is conventional for Linux metadata-preserving backups.
Linux Processes, Packages and Services examples
1Find and control a busy task
17 steps
- 1IntroductionStart with the running work
A terminal has become sluggish while a long compression job runs. Before stopping anything, connect the visible symptom to a process and a resource.
You will move from a process snapshot to live CPU and memory evidence, then decide how to pause, stop or lower the priority of work. The PID identifies the process; the shell’s job number serves a different purpose when moving it between foreground and background.
- 2ExplanationFind the owner and identity
Run
ps -effor a system-wide snapshot with PID and PPID. A command started from your terminal is usually a child of that shell.For CPU and memory columns, use
ps aux. A program can have several running instances, each with its own PID. Check both the command and owner when choosing a target: a familiar name alone may identify several processes, and a PID can be reused after its earlier process exits. - 3ExampleRead CPU time correctly
A ps row shows START
09:00, TIME0:08and stateS. The program began at 09:00 and has accumulated eight seconds of CPU work. It is sleeping while waiting for an event.The elapsed time since startup is not the TIME field. A service can wait for requests for hours and use very little CPU. Use
pgrep -a NAMEto find relevant command lines and/proc/PID/statuswhen you need the kernel’s detailed view. - 4ChallengeInterpret a waiting server
A server started yesterday. Its ps row has TIME
0:12, TTY?and stateS. Is this evidence that it failed to run for most of the day? Explain the three fields.---reveal---
No. It has used 12 seconds of CPU work, has no controlling terminal and is currently sleeping. Waiting for requests is normal service behavior. These fields do not report how many hours the server has been available or whether a particular request succeeded.
- 5ExplanationWatch the resource that changes
Open
top. PressPfor CPU ordering,Mfor memory and1for individual CPUs. Pressqto quit.Read the summary with the process list. High user CPU work suggests computation; high
wadirects attention toward outstanding I/O, and highstin a virtual machine indicates host CPU time withheld from the guest. RES measures resident RAM; a large VIRT allocation alone is a poor measure of physical memory use. - 6ExamplePut load beside CPU capacity
Suppose
nprocreports 4 and a mostly CPU-bound workload shows load6.00, 5.20, 3.10. With little I/O waiting, the recent load means more runnable tasks than four CPUs can execute at once.The one-minute value exceeds the longer averages, indicating a recent rise. Linux load also counts uninterruptible waits, so repeat this comparison with the CPU summary and process states in view; the number is not a CPU percentage.
- 7Key InsightRead available RAM before free
free -hcan show little completely free RAM while several GiB remain available. Linux uses spare RAM for cache and can reclaim much of it for new work.Available estimates capacity without swapping. Watch low available memory together with increasing swap use for stronger evidence of pressure. If the kernel kills work because memory is exhausted, an OOM record in
sudo journalctl -kcan explain the sudden exit. - 8ChallengeChoose the resource to investigate
A server has many state-D tasks, high
wa, low user CPU use and plenty of available RAM. Which resource should you investigate first, and why can its load still be high?---reveal---
Investigate storage or other I/O waits first. Linux includes uninterruptible tasks in load, so a high load can coexist with idle CPUs. The memory figures do not point toward an immediate RAM shortage, and high load alone cannot identify CPU computation as the cause.
- 9ExplanationAsk for a clean exit first
A signal asks a process to act.
kill PIDsends SIGTERM, which gives the program an opportunity to save state and close resources. SIGKILL forces exit without its cleanup code.Verify the target, send TERM, allow time and check again before escalating. A PID that now belongs to a new command is a different process. For a service supervised by systemd, request
sudo systemctl stop NAMEthrough its manager. - 10ExamplePause and continue deliberately
kill -STOP 5120pauses process 5120;kill -CONT 5120resumes it. The process keeps its memory and open files during the pause.Ctrl+Z sends a pause request to terminal foreground work, while Ctrl+C sends an interrupt that normally ends it. A zombie is already dead and cannot be killed again. A task in an uninterruptible storage wait may remain visible until that wait returns, even after a forceful termination signal.
- 11ChallengeKeep a managed service stopped
A managed worker restarts after you kill its PID. You want the worker stopped for maintenance now. What action fits, and why is killing the new PID a poor routine?
---reveal---
Use
sudo systemctl stop NAME. The service manager understands that this stop is intentional and handles the managed processes. Killing another PID can repeat the same failure-recovery loop because systemd may treat the process exit as a reason to restart the worker. - 12ExampleMove a job without losing it
Start
sleep 300in the foreground, then press Ctrl+Z. Bash reports the job as Stopped.bg %1resumes job 1 while returning the prompt, andfg %1brings it forward again.The
%1is a shell-local job selection, not PID 1. A stopped job has not finished: it retains resources. If output from background work disrupts the terminal, send it to a file before leaving the task running. - 13TipPrepare a task for logout
For a new long task, use
nohup ./long-task.sh > task.log 2>&1 &. Nohup makes it ignore HUP, redirection puts both output streams in a file, and the ampersand backgrounds it.Each part has a separate job. An ampersand alone does not protect against terminal closure. Bash’s
disown %1can remove an existing job from the shell’s job table, but its input and output still need suitable destinations. - 14ExplanationLower priority without imposing a speed cap
Start heavy work with
nice -n 10 COMMANDfrom the usual nice value 0, or set a running task withrenice -n 15 -p PID. Higher nice values lower ordinary CPU scheduling priority.The range is -20 through 19. An ordinary user can generally make their own work less competitive; raising its priority usually needs root. A nice-19 task still uses an idle CPU fully, and niceness does not set disk-access priority.
- 15ChallengeAdjust a live background job
Your own background compression task is PID 9328, at nice 0. You want it to give competing interactive work more CPU opportunity without pausing it. What command and effect fit?
---reveal---
renice -n 15 -p 9328lowers its CPU priority by raising its nice value. The task keeps running; it receives less opportunity under CPU competition. Sending STOP would pause it entirely, while choosing a negative nice value would raise its priority. - 16ChallengeConnect the evidence to a response
A backup is active at nice 0. Top shows it using several CPUs, low I/O wait and enough available RAM; interactive work is slow. Must you kill the backup to help the interactive task?
---reveal---
No. The evidence supports CPU competition, so increasing the backup’s nice value can give the interactive work more opportunity while the backup continues. If stopping later becomes necessary, identify the process again and request a clean exit before considering force.
- 17RecapMatch the action to the evidence
Use ps and pgrep to establish identity, then top, free and load to understand pressure. Read state before interpreting a process that seems stuck.
A clean exit, pause, background move and priority change solve different problems. Keep service control with systemd, distinguish local jobs from PIDs and verify the result after changing running work.
2Build a useful hardware report
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCollect facts that answer the requirement
- 2ExplanationName the system layers
- 3ExampleCount the CPU layout
- 4ExplanationCompare installed and usable memory
- 5ChallengeCheck a minimum requirement
- 6ExampleRead a storage tree
- 7ExplanationConnect a device with its driver
- 8ChallengeIdentify a newly connected disk
- 9ChallengeDistinguish capacity from driver support
- 10RecapMake the report specific
3Install software and trace what changed
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep files and package records connected
- 2ExplanationChoose the repository tool
- 3Key InsightA dependency belongs in the plan
- 4ChallengeExplain the extra packages
- 5ExampleRefresh before installing
- 6ExplanationRead what an upgrade permits
- 7TipDecide what removal should keep
- 8ChallengeSeparate refreshing from applying
- 9ExampleFollow a command to its owner
- 10ExplanationSearch beyond installed files
- 11ChallengeChoose the direction of the query
- 12ConnectionRelate a fault to recent maintenance
- 13ChallengeRepair from the evidence
- 14RecapCheck the state you actually need
4Run a service now and after reboot
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk two state questions
- 2ExampleRead Loaded and Active
- 3Key InsightAn active unit need not have a live process
- 4ChallengeInterpret disabled but running
- 5ExplanationChoose now, later or both
- 6ExampleApply an application configuration
- 7ChallengeBlock a service without overlooking its process
- 8ExplanationRead the effective unit definition
- 9ExampleDescribe a simple foreground server
- 10ExampleMake an override survive upgrades
- 11ChallengeApply a directly edited command
- 12Key InsightRestart rules still honor a requested stop
- 13ChallengeVerify a service after a unit change
- 14RecapKeep each layer distinct
5Find the cause of a failed service
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBegin with an observable symptom
- 2ExplanationSelect the service and attempt
- 3ExampleKeep useful low-priority messages
- 4ChallengeSearch the correct boot
- 5ExplanationFind application and rotated logs
- 6ExampleCheck a silent application exit
- 7ChallengeChoose an older text source
- 8ExampleStart with the first causal error
- 9ExampleFollow a busy port to its owner
- 10Key InsightUse result codes to choose the next check
- 11ChallengeRecover from a rate-limited failure
- 12ChallengeVerify without losing evidence
- 13RecapLet each finding narrow the next step
6Make an archive you can restore
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPlan the restore before the archive
- 2ExplanationSeparate collection from size reduction
- 3ExampleCreate useful relative paths
- 4ExampleInspect and extract in separate steps
- 5ChallengePredict the extraction layout
- 6TipKeep f next to its filename
- 7ExplanationKnow which originals remain
- 8ExampleChoose a format for the work
- 9ChallengeKeep one log while compressing it
- 10ChallengeCheck both the copy and the contents
- 11RecapUse the format and the checks that fit
Linux Processes, Packages and Services practice questions
Set 1: Apply everyday Linux maintenance commands10 Practice Questions
Question 1 of 10
app.log.2.gz. How can you search that older file directly?Show answerHide answer
Question 2 of 10
[3] 9026 after starting a job. How do you bring that job to the foreground?Show answerHide answer
Question 3 of 10
12.0, 8.0, 4.0. What is the best interpretation?Show answerHide answer
Question 4 of 10
Kernel driver in use line. What should you investigate next?Show answerHide answer
Question 5 of 10
/usr/bin/less?Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
203/EXEC. Its journal contains no application startup message. The unit file names /opt/worker/run, but that path is absent. What repair sequence fits the evidence?Show answerHide answer
Question 9 of 10
report.log with gzip and retain the uncompressed file. What command fits?Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Read processes, packages and service states10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
06:20 and TIME 0:04. What does TIME report?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
sudo apt update. What has changed when it succeeds?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
enabled and inactive (dead). How should you read that combination?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
/srv/notes/day.txt, owned by root, with tar -czf notes.tar.gz -C /srv notes. As a regular user, you then run tar -xzf notes.tar.gz -C /tmp/inspect into that empty existing directory. What path and owner does the restored file normally have?Show answerHide answer
Save this lesson to see this answer.
Set 3: Connect evidence with the right action10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Z, and its parent remains running. Why does sending SIGKILL to that PID fail to remove the entry?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
pgrep finds two data-export processes: PID 8550 is your data-export --daily; PID 8551 is another user’s data-export --weekly. You want only your daily job to exit cleanly. What action fits?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
active (exited) after completing a one-time setup task successfully. What does this state mean?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
journalctl -p err?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Diagnose maintenance problems across tools10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
/usr/bin/scan is absent. You want to discover which repository package supplies that exact path. What query fits?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
/dev/sdb yesterday. Today another device was connected first, and a write to the wrong disk would erase needed files. What should determine your target now?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
After=network.target establish by itself?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
bundle/a.txt and bundle/b.txt. You want only b.txt restored. Which member name should you request?Show answerHide answer
Save this lesson to see this answer.
Set 5: Plan and verify complete Linux repairs10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
nginx -t now finds a syntax error. What sequence applies both intended changes with a tested configuration?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Active state
Architecture
Archive
Archive member
Autoremove
Available memory
B
Background job
Block device
/dev.C
Candidate version
Checksum
Compression
Configuration test
nginx -t after a correction gives a reason to proceed with the planned reload or restart.D
Daemon reload
Dependency
Device file
/dev, through which software accesses a device represented by the kernel./dev/nvme0n1p2 identifies a partition rather than a directory of files.Driver
Drop-in
E
Enablement
ExecStart
./worker has a relative slash-containing path and is not a valid executable form.Exit status
Extraction
F
File metadata
File ownership query
rpm -qf for an installed executable whose package name you do not know on an RPM system.Firmware table
Foreground job
fg %2, keyboard shortcuts such as Ctrl+C act on the job now in the foreground.G
Gzip
I
I/O wait
Installed version
J
Job number
[2] 7164, fg %2 selects the job; 7164 identifies its process at the operating-system level.Journal vacuuming
K
Kernel log
Kernel module
L
Load average
Log rotation
Logical CPU
M
Mask
/dev/null, including manual and dependency starts.MemTotal
/proc/meminfo, excluding memory reserved before ordinary use.N
Nice value
O
OOM killer
P
Package
Package lock
Package metadata
Package-list refresh
apt update, a newer application can be listed as available while the old one remains installed.Persistent journal
/var/log/journal, allowing earlier boots to be queried until retention removes them.Physical core
PID
Port conflict
PPID
Priority
Process
sleep commands create two processes even though they run the same program.Purge
R
Reload
Repository
Restart
Restart policy
systemctl stop keeps the service stopped.Ring buffer
RSS
S
Service
SIGKILL
Signal
Signature verification
SIGSTOP
SIGTERM
Start-rate limit
Swap
Syslog
systemd
Systemd journal
T
Target
Transaction
U
Unit
nginx.service identifies the unit as a service rather than a socket or target.Unit file
Upgrade
UUID
V
Volatile journal
/run/log/journal so they are lost at shutdown rather than carried into the next boot.X
Xz
Z
ZIP
zip -r to package a directory and its contents for colleagues using Windows or macOS.Zombie
- 1Linux and Open Source
- 2Linux Command Line
- 3Linux Text Processing
- 4Shell Scripting
- 5Linux Users, Groups and Permissions
- 6Linux Processes, Packages and Services
- 7Linux Storage and Networking
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.