Skip to main content

Chapter 02 · Must‑Know Linux Commands for Beginners

Chapter Overview

Experienced administrators meet requirements by combining the right commands with the right parameters—achieving goals quickly while conserving system resources. This chapter first explains how the kernel and the shell cooperate, then outlines four core strengths of the Bash interpreter. We also drill into the command + parameters + target pattern so you can execute Linux commands precisely.

We selected more than fifty essential Linux commands for newcomers, covering system operation, status monitoring, directory management, file handling, archiving/compression, and search. These commands are grouped into focused sections so you can master them step by step and build a solid foundation for learning more advanced tools and services later on.

2.1 The Shell: Powerful and Practical

A complete computer consists of CPU, controller, memory, and input/output devices. The operating system kernel coordinates these components: managing hardware resources, protecting system security, controlling process execution, managing memory, and handling system calls—work that is critical for stable operation.

Like editing the Windows registry, directly changing Linux kernel parameters requires expertise and is risky—an error can crash the system. Rather than tweaking kernel parameters yourself, manage the machine through user‑space programs and services built on top of the kernel’s system‑call interfaces.

As shown in Figure 2‑1, people cannot operate hardware directly (imagine someone talking to a bare hard disk—it’s absurd). Hardware is managed by the kernel, but the kernel is complex and sensitive, so users should not access it directly. While you could invoke kernel APIs one by one to achieve a goal, even a simple task like “send a message across the internet” may require dozens of system‑call invocations—impractical in day‑to‑day work. Closest to end users are service programs: complete applications that integrate many APIs—for example, WeChat or QQ.

Figure 2‑1 Users and hardware

Service programs act as interpreters between people and hardware. If a computer were a society, services would be translators: they translate a user’s request into instructions the hardware can execute, then present the results in a human‑readable form. Back and forth like this, users gain access to hardware resources.

Shell icon

Seeing hardware wrapped in layers may remind you of a snail’s shell. In English, “shell” is exactly the term for terminal programs; the industry calls the user’s terminal program a shell—easy to remember.

Shell is the umbrella term for terminal programs. It serves as the translator between people and the kernel (hardware). Users “tell” the terminal a command; the terminal calls the corresponding program or service to get the job done. Most mainstream Linux distributions—including Red Hat Enterprise Linux (RHEL)—use Bash (Bourne‑Again Shell) as the default command interpreter. Bash not only executes commands, it also provides script programming for batch automation, history tracking, job control, and powerful environment variables—key reasons it’s the most popular shell on Linux. In short, Bash is widely adopted thanks to four core strengths:

Retrieve previously executed Linux commands with the Up/Down arrows.
Complete a command, parameter, or path with the Tab key after typing just a few characters.
Write batch scripts to automate complex tasks.
Manage powerful environment variables.

Historically, in the 1970s AT&T commercialized UNIX, including the widely used sh (Bourne Shell) command interpreter. Because the GNU Project valued openness and resisted restrictive copyrights, an open replacement was urgently needed; Bash arrived in 1989. Bash implements all functionality of the Bourne Shell and adds numerous improvements, quickly winning over operations professionals. As you continue learning and working, you’ll experience the power and elegance of the Linux command line—and likely come to love it.

Tips:

Shell is the category; Bash is one member. As in society where “translator” is a profession made up of many practitioners, Bash is one outstanding member of the Shell family.

Linux has many excellent GUI tools (for example, the Logical Volume Manager, LVM) that greatly reduce mistakes—worthy of praise. But many GUIs simply call underlying command scripts and are often designed for narrow tasks, sacrificing the flexibility and fine‑grained control of native commands. GUIs also consume more resources. Experienced administrators often avoid installing any GUI on servers; they connect remotely and work in the shell—efficient and reliable.

2.2 Essentials for Running Commands

Since we have such a handy “translator,” we should learn how to talk to it. To complete tasks accurately and efficiently, the command alone is not enough—you tailor its parameters to match the job.

For example, generic tools can accomplish many tasks but may be inefficient or imprecise. It’s like slicing sushi with a chef’s knife—you’ll fling rice everywhere. A sushi knife, with its air holes and specialized shape, is tuned for the job. Likewise, Linux offers many purpose‑built tools with parameters suited to specific tasks. With learning and experience, you’ll come to understand Linux commands deeply and know how to choose the right command and parameters for each scenario.

The common structure for Linux commands is:

command [parameters] [target]

command: the “verb,” expressing what to do: create a user, view a file, reboot a system.

parameters: adjustments that tailor the command to the job, like tailoring clothing for a better fit. Examples: create a user with UID 888; show only the first 20 lines of a file. Parameters come in long form (full names) and short form (single‑letter abbreviations), prefixed by -- and - respectively (Table 2‑1).

Table 2‑1 Long vs. short parameter forms

TypeExample
Longman --help
Shortman -h

target: the object to act on: a file, directory, user, etc. Examples: create user “xiaoming”; open file “payroll.xlsx”; reboot the host at 192.168.10.10.

Tips:

Separate the command, its parameters, and the target with spaces. Linux is case‑sensitive.

Throughout this book, optional parameters are shown in square brackets (for example, ls [target]). Required arguments are shown without brackets. This notation helps you read commands accurately.

Beginners often stumble over complex parameter sets whose values change with the command and the situation. “With so many commands, how do I know what a command does? When I meet an unfamiliar command at work, how do I learn its parameters?” Start with man—the built‑in manual system. For true beginners, Figures 2‑2 to 2‑5 walk through running commands on RHEL 10.

As shown in Figure 2‑2, choose Super User at login (the root account) and enter the password you set (see Figure 1‑40 if you’ve forgotten).

Figure 2‑2 Switch to the root administrator

If you log in as the linuxprobe user, some commands later in this chapter will fail due to insufficient privileges. We need adequate privileges to complete the labs. We’ll discuss “root vs. regular users and how to choose in production” in Chapter 5.

Tips:

After logging in, if you see a prompt to register, click the × in the upper‑right to close it. Unless you want a paid Red Hat subscription for the latest software and vendor support, you can ignore it. Later we’ll build local repositories so all labs run smoothly.

Click the Red Hat icon at top‑left and choose the terminal to open the Bash interpreter (Figure 2‑3).

Figure 2‑3 Open the terminal

In the terminal, type man man to view the manual for the man command itself (Figure 2‑4). Press q to quit (Figure 2‑5).

Figure 2‑4 View help for the man command

Figure 2‑5 man output

Linux strictly distinguishes case. Compare the following—only lowercase man works:

root@linuxprobe:~# Man
bash: Man: command not found...
Similar command is: 'man'
root@linuxprobe:~# MAN
bash: MAN: command not found...
Similar command is: 'man'
root@linuxprobe:~# man
What manual page do you want?
For example, try 'man man'.

Common man keys appear in Table 2‑2.

Table 2‑2 Common man keys

KeyAction
SpacePage down
Page DownPage down
Page UpPage up
HomeJump to first page
EndJump to last page
/Search downward (for example, /linux)
?Search upward (for example, ?linux)
nNext match
NPrevious match
bPage up
gGo to first page
hHelp
uScroll up half a page
dScroll down half a page
qQuit

man pages are often long. Knowing the structure helps (Table 2‑3).

Table 2‑3 Common man sections

SectionMeaning
NAMECommand name
SYNOPSISSyntax overview
DESCRIPTIONDescription
EXAMPLESExamples
OVERVIEWOverview
DEFAULTSDefaults
OPTIONSAvailable parameters
ENVIRONMENTEnvironment variables
FILESFiles used
SEE ALSORelated docs
HISTORYMaintenance history and contacts

Before your input, you see a prompt such as root@linuxprobe:~#. It shows context: user root, short hostname linuxprobe, working directory ~ (your home; Chapter 6 explains it), and # indicates admin; $ indicates an unprivileged user (Figure 2‑6).

Figure 2‑6 Terminal prompt

Four handy shortcuts you’ll use constantly:

Tab — The most frequently used key in Bash. It completes commands, parameters, and paths.

root@linuxprobe:~# re<Tab><Tab>
read readarray readelf readlink readonly readprofile realpath reboot ...
root@linuxprobe:~# reb<Tab>
root@linuxprobe:~# reboot

Ctrl+C — Terminate the foreground process immediately. Useful for stopping a hung command or a command you started by mistake:

root@linuxprobe:~# watch -n 1 uptime
Every 1.0s: uptime linuxprobe.com: Mon Mar 10 20:05:39 2025
20:05:10 up 46 min, 2 users, load average: 0.06, 0.05, 0.01
<Ctrl>+<C>
root@linuxprobe:~#

Ctrl+D — Send end‑of‑input.
Ctrl+L — Clear the screen.

2.3 Essential System Commands

This chapter of Learn Linux the Right Way distills lessons from dozens of training cohorts. You may notice that a few commands you’ve seen elsewhere don’t appear here. That’s intentional—we focus on pairing commands with real‑world tasks so you internalize how Linux is used in practice, instead of memorizing a long, context‑free list.

  1. echo

The echo command prints text or the value of a variable to the terminal.
Syntax: echo [STRING] [$VARIABLE]

It’s one of the most frequently used Linux commands. To print a literal string, run echo STRING. To print a variable’s value, prefix its name with $.

Example: print a specific string to the terminal:

root@linuxprobe:~# echo LinuxProbe.com

Output:

LinuxProbe.com

Now read the value of the SHELL variable and print it:

root@linuxprobe:~# echo $SHELL
/bin/bash
  1. date

The date command shows or sets the system’s date and time.
Syntax: date [OPTIONS] [+FORMAT] [TIME]

Supply a format that begins with + to print the date/time in a specific layout. This is extremely handy for automating backups—for example, naming an archive backup-2025-05-18.tar.gz using the YYYY-MM-DD pattern so its timestamp is obvious at a glance. Common date format specifiers are listed in Table 2‑4.

Table 2‑4. Common date format specifiers

SpecifierMeaning
%SSeconds (00–59)
%MMinutes (00–59)
%HHours (00–23)
%IHours (00–12)
%mMonth (1–12)
%pAM/PM
%aAbbreviated weekday (e.g., Sun)
%AFull weekday (e.g., Sunday)
%bAbbreviated month (e.g., Jan)
%BFull month (e.g., January)
%yYear without century (e.g., 25)
%YFour‑digit year (e.g., 2025)
%dDay of month
%jDay of year
%nNewline
%tTab

Show the current time using the default format:

root@linuxprobe:~# date
Mon Mar 10 08:36:57 PM CST 2025

Show the current time as YYYY-MM-DD HH:MM:SS:

root@linuxprobe:~# date "+%Y-%m-%d %H:%M:%S"
2025-03-10 20:37:09

Set the system clock to May 18, 2025 08:30:00:

root@linuxprobe:~# date -s "20250518 8:30:00"
Sun May 18 08:30:00 AM CST 2025

Use %j to print the ordinal day of the year (useful when comparing backup recency—the larger the number, the later in the year):

root@linuxprobe:~# date "+%j"
138
  1. timedatectl

The timedatectl command manages the system clock and time zone (time‑date control).
Syntax: timedatectl [OPTIONS]

If your clock is off by only a few minutes, adjust it directly. If it’s off by hours, verify the time zone as well. Common timedatectl subcommands appear in Table 2‑5.

Table 2‑5. Common timedatectl subcommands

SubcommandDescription
statusShow status information
list-timezonesList known time zones
set-timeSet the system time
set-timezoneSet the active time zone
set-ntpEnable/disable NTP

View the current time and time zone:

root@linuxprobe:~# timedatectl status
Local time: Sun 2025-05-18 08:32:23 CST
Universal time: Sun 2025-05-18 00:32:23 UTC
RTC time: Mon 2025-03-10 12:39:43
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: no
NTP service: active
RTC in local TZ: no

If your time zone isn’t Asia/Shanghai, set it explicitly:

root@linuxprobe:~# timedatectl set-timezone Asia/Shanghai

If the time is still wrong, disable NTP before setting the clock manually—otherwise it may be synced back automatically:

root@linuxprobe:~# timedatectl set-ntp false
root@linuxprobe:~# timedatectl set-time 2025-05-18

To adjust only the time:

root@linuxprobe:~# timedatectl set-time 9:30
root@linuxprobe:~# date
Sun May 18 09:30:02 AM CST 2025
  1. reboot

The reboot command restarts the system. It touches hardware‑level resources, so non‑privileged users may be denied; run it as root:

root@linuxprobe:~# reboot
  1. poweroff

The poweroff command shuts down the system. As with reboot, run it with sufficient privileges (typically as root):

root@linuxprobe:~# poweroff
  1. wget

wget downloads files from the web at the command line (World Wide Web “get”).
Syntax: wget [OPTIONS] URL

wget lets you retrieve files without opening a browser. If you’re new to Linux administration, first skim the parameters and the examples below. In later chapters—after you configure networking—you can return and practice. Common parameters are shown in Table 2‑6.

Table 2‑6. Common wget parameters

ParameterDescription
-bRun in the background
-PSave to a specified directory
-tMaximum number of retries
-cResume a partial (interrupted) download
-pDownload all resources needed by a page (CSS, JS, images, etc.)

Tips: These examples fetch files from the public internet. If your VM lacks outbound connectivity, you’ll see timeouts. That’s expected—feel free to skip the hands‑on steps for now.

Download the latest PDF edition of this book from the companion site:

root@linuxprobe:~# wget https://www.linuxprobe.com/docs/LinuxProbe.pdf
--2025-05-18 09:36:47-- https://www.linuxprobe.com/docs/LinuxProbe.pdf

Resolving www.linuxprobe.com (www.linuxprobe.com)... 117.72.45.242
Connecting to www.linuxprobe.com (www.linuxprobe.com)|117.72.45.242|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 23335661 (22M) [application/pdf]
Saving to: ‘LinuxProbe.pdf’

LinuxProbe.pdf 100%[===================>] 22.25M 1.54MB/s in 14s

2025-05-18 09:37:02 (1.54 MB/s) - ‘LinuxProbe.pdf’ saved [23335661/23335661]

Recursively mirror all pages and files under https://www.linuxprobe.com, saving them beneath a directory named www.linuxprobe.com in the current path:

root@linuxprobe:~# wget -r -p https://www.linuxprobe.com
--2025-05-18 09:37:29-- https://www.linuxprobe.com/
Resolving www.linuxprobe.com (www.linuxprobe.com)... 117.72.45.242
Connecting to www.linuxprobe.com (www.linuxprobe.com)|117.72.45.242|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘www.linuxprobe.com/index.html’

www.linuxprobe.com/ [ <=> ] 67.40K --.-KB/s in 0.008s
…some output omitted…
  1. ps

ps shows process status (process status).
Syntax: ps [OPTIONS]

The first time you run ps, the volume of output can be surprising. Power users typically combine ps with the pipeline tools in Chapter 3 to extract the PID of a specific service. Common parameters appear in Table 2‑7.

Table 2‑7. Common ps parameters

ParameterDescription
-aShow all processes (including those of other users)
-uInclude user and other detailed columns
-xInclude processes without a controlling terminal

Linux runs many processes at any given time. Managing them well helps overall performance. The five most common process states are running, interruptible sleep, uninterruptible sleep, zombie, and stopped:

R (Running): The process is running or waiting on the run queue.
S (Interruptible sleep): The process is sleeping; it will wake on a condition or signal.
D (Uninterruptible sleep): The process is in uninterruptible sleep, typically waiting for I/O.
Z (Zombie): The process has exited, but its descriptor remains until the parent calls wait4().
T (Stopped): The process has been stopped after receiving a stop signal.

Additional flags may appear with states: high priority (<), low priority (N), locked in memory (L), has children (s), multithreaded (l).

A sample of ps aux output is shown in Table 2‑8 (only a subset of rows is shown; production output does not include the explanatory row).

Table 2‑8. Sample process list (ps aux)

USERPID%CPU%MEMVSZRSSTTYSTATSTARTTIMECOMMAND
UserProcess IDCPU usage %Memory usage %Virtual memory (KB)Resident memory (KB)TerminalStateStart timeCPU timeCommand
root10.30.65227224944?Ss09:320:01/usr/lib/systemd/systemd --switched-root --system --deserialize=44 rhgb
root20.00.000?S09:320:00[kthreadd]
root30.00.000?S09:320:00[pool_workqueue_release]
root40.00.000?I09:320:00[kworker/R-rcu_gp]
root50.00.000?I09:320:00[kworker/R-sync_wq]
root60.00.000?I09:320:00[kworker/R-slub_flushwq]
root90.00.000?I09:320:00[kworker/0:0H-events_highpri]
root100.00.000?I09:320:00[kworker/0:1-events]

Tips:
Many commands support both short and long parameters. Short parameters can be combined (e.g., -a -x-ax), but long parameters cannot be combined and cannot be mixed with short parameters when combined. ps also allows parameters without a leading dash, hence the common ps aux form.

  1. pstree

pstree displays processes in a tree, showing parent/child relationships. Run it with no arguments to view the current hierarchy:

root@linuxprobe:~# pstree
systemd─┬─ModemManager───3*[{ModemManager}]
├─NetworkManager───3*[{NetworkManager}]
├─VGAuthService
├─accounts-daemon───3*[{accounts-daemon}]
├─atd
├─auditd─┬─sedispatch
│ └─2*[{auditd}]
├─avahi-daemon───avahi-daemon
├─colord───3*[{colord}]
…some output omitted…
  1. top

top dynamically monitors process activity and system load in real time. Earlier commands showed static snapshots, but top updates continuously—think of it as Linux’s “power user” version of Windows Task Manager.

The top interface is shown in Figure 2‑7.

Figure 2‑7 The top runtime interface

In the header section (first five lines), the fields mean:

Line 1: System time, uptime, logged‑in users, and load averages (1‑, 5‑, 15‑minute windows; lower is lighter load).
Line 2: Total processes, running, sleeping, stopped, and zombie counts.
Line 3: CPU usage breakdown by user, system, “nice‑adjusted,” idle, etc. For example, 99.9 id means 99.9% of CPU time is idle.
Line 4: Physical memory—total, free, used, and buffers/cache.
Line 5: Swap (virtual memory)—total, free, used, and pre‑allocated.

  1. nice

nice adjusts a process’s scheduling priority.
Syntax: nice -n ADJUSTMENT COMMAND

In top, the PR and NI columns show priority and “niceness.” Lower numbers mean higher priority. Niceness ranges from −20 (highest priority) to 19 (lowest). In production, lower the priority of less critical jobs so urgent services get more CPU and memory. Example: start bash with the highest priority:

root@linuxprobe:~# nice -n -20 bash
  1. pidof

pidof prints the PID(s) of a named program.
Syntax: pidof [OPTIONS] PROGRAM

Every process has a unique PID during its lifetime. For example, to get the PID of the sshd daemon:

root@linuxprobe:~# pidof sshd
1340
  1. kill

kill sends a signal to a process; by default it requests termination.
Syntax: kill [OPTIONS] PID

Terminate the process we just found with pidof (equivalent to forcibly stopping sshd in this example):

root@linuxprobe:~# kill 1340

If the process does not exit, send signal 9 (SIGKILL), which cannot be trapped or ignored:

root@linuxprobe:~# kill -9 1340
  1. killall

killall terminates all processes with a given program name.
Syntax: killall [OPTIONS] PROGRAM

Complex services often spawn multiple cooperating processes. Rather than issuing kill repeatedly, use killall to end them all at once.

Example with the httpd service (note that on some distributions it may not be installed by default; follow along for the flow and revisit after the web server chapter):

root@linuxprobe:~# pidof httpd
13581 13580 13579 13578 13577 13576
root@linuxprobe:~# killall httpd
root@linuxprobe:~# pidof httpd
root@linuxprobe:~#

If a foreground command is running and you want to stop it, press Ctrl+C to send SIGINT. If a command’s verbose output clutters your screen while you need to keep working, append & to run it in the background.

2.4 System Status and Diagnostics

To administer Linux servers with confidence, you must be able to read the system’s health quickly. In this chapter of Learn Linux the Right Way, we walk through commands that report on network interfaces and connectivity, the kernel and OS build, system load, memory usage, active terminals, login history, command history, and basic support/diagnostics collection. These tools are genuinely useful in day‑to‑day operations—master them.


  1. ifconfig

ifconfig shows network interface configuration and status (interface configurator).
Syntax: ifconfig [OPTIONS] [INTERFACE]

When reviewing ifconfig output, focus on: the interface name, the IPv4 address after inet, the MAC address after ether, and counters for RX (received packets) and TX (transmitted packets).

root@linuxprobe:~# ifconfig
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.10.10 netmask 255.255.255.0 broadcast 192.168.31.255
inet6 fe80::20c:29ff:fee5:e733 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:e5:e7:33 txqueuelen 1000 (Ethernet)
RX packets 27660 bytes 27151953 (25.8 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 9449 bytes 652999 (637.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 120 bytes 10704 (10.4 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 120 bytes 10704 (10.4 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

RHEL 5/6 used eth0, eth1, …. RHEL 7 introduced names such as eno16777736. RHEL 8/9/10 commonly show ens160, ens192, and the like. Seasoned admins can often infer the OS generation from interface names alone.


  1. uname

uname prints kernel and machine information (UNIX name).
Syntax: uname [OPTIONS]

Use -a to display the kernel name and release, hostname, build time, hardware name/platform/CPU, and OS name:

root@linuxprobe:~# uname -a
Linux linuxprobe.com 6.12.0-55.9.1.el10….x86_64 #1 SMP PREEMPT_DYNAMIC Mon Sep 23 04:19:12 EDT 2025 x86_64 GNU/Linux

To view the distribution release details, read the redhat-release file:

root@linuxprobe:~# cat /etc/redhat-release 
Red Hat Enterprise Linux release 10.0

  1. uptime

uptime reports how long the system has been running and the current load averages. Run it with no arguments:

root@linuxprobe:~# uptime
09:55:09 up 22 min, 2 users, load average: 0.06, 0.05, 0.06

The three load averages are the 1‑, 5‑, and 15‑minute moving averages. Lower is lighter. As a practical rule in production, aim for ≈1 per CPU core and avoid sustained loads above 2× the core count. An idle machine is safe but wasteful; managers want their hardware doing useful work.


  1. free

free shows memory and swap usage.
Syntax: free [OPTIONS]

Use -h for a human‑readable view (GiB/MiB). Below is representative output from free -h (Chinese annotations in the original are removed here for clarity):

root@linuxprobe:~# free -h

Table 2‑9. Output fields from free -h

totalusedfreesharedbuff/cacheavailable
Mem:3.8Gi1.5Gi1.8Gi14Mi773Mi2.3Gi
Swap:2.0Gi0B2.0Gi

Without -h, units default to KB, which is tedious to read on large-memory servers.


  1. who

who lists users currently logged into the system and their terminals. Run with no arguments:

root@linuxprobe:~# who

Table 2‑10. Sample who output

UsernameTTYLogin time
rootseat02025‑05‑18 09:36 (login screen)
roottty22025‑05‑18 09:36 (tty2)

If a user is connected remotely, you’ll also see the remote IP address.


  1. last

last shows historical login information. The system records each login event in a log you can review later:

root@linuxprobe:~# last
root tty2 tty2 Sun May 18 09:36 still logged in
root seat0 login screen Sun May 18 09:36 still logged in
reboot system boot 6.11.0-0.rc5.23. Sun May 18 09:32 still running
root tty2 tty2 Sun May 18 09:31 - down (00:01)
root seat0 login screen Sun May 18 09:31 - down (00:01)

wtmp begins Sun Mar 9 02:33:32 2025

  1. ping

ping tests reachability between hosts using ICMP.
Syntax: ping [OPTIONS] HOST

Common parameters (Table 2‑11):

ParameterPurpose
-cTotal number of requests to send
-iInterval between requests (sec)
-WPer‑request timeout (sec)

An online host (192.168.10.10) replies like this:

root@linuxprobe:~# ping -c 4 192.168.10.10
PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data.
64 bytes from 192.168.10.10: icmp_seq=1 ttl=64 time=0.054 ms
64 bytes from 192.168.10.10: icmp_seq=2 ttl=64 time=0.053 ms
64 bytes from 192.168.10.10: icmp_seq=3 ttl=64 time=0.052 ms
64 bytes from 192.168.10.10: icmp_seq=4 ttl=64 time=0.042 ms

--- 192.168.10.10 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3090ms
rtt min/avg/max/mdev = 0.042/0.050/0.054/0.004 ms

A non‑responsive host (192.168.10.20) shows:

root@linuxprobe:~# ping -c 4 192.168.10.20
PING 192.168.10.20 (192.168.10.20) 56(84) bytes of data.
From 192.168.10.10 icmp_seq=1 Destination Host Unreachable
From 192.168.10.10 icmp_seq=2 Destination Host Unreachable
From 192.168.10.10 icmp_seq=3 Destination Host Unreachable
From 192.168.10.10 icmp_seq=4 Destination Host Unreachable

--- 192.168.10.20 ping statistics ---
4 packets transmitted, 0 received, +4 errors, 100% packet loss, time 3051ms
pipe 3

On Windows, ping sends 4 requests by default. On Linux, ping runs until you stop it (Ctrl+C) unless you set a count with -c.


  1. tracepath

tracepath shows the route packets take to a destination (each hop).
Syntax: tracepath [OPTIONS] IP_or_DOMAIN

When hosts cannot ping each other, investigate the path. tracepath lists every hop so you can spot routing or filtering that drops packets:

root@linuxprobe:~# tracepath www.linuxprobe.com
1?: [LOCALHOST] pmtu 1500
1: no reply
2: 11.223.0.189 5.954ms asymm 1
3: 11.223.0.14 6.256ms asymm 2
4: 11.220.159.62 3.313ms asymm 3
5: 116.251.107.13 1.841ms
6: 140.205.50.237 2.416ms asymm 5
7: 101.95.211.117 2.772ms
8: 101.95.208.45 40.839ms
9: 101.95.218.217 13.898ms asymm 8
10: 202.97.81.162 8.113ms asymm 9
11: 221.229.193.238 15.693ms asymm 10
12: no reply
13: no reply
14: no reply
15: no reply
16: no reply

  1. netstat

netstat displays network connections, routing tables, interface statistics, and more (network status).
Syntax: netstat [OPTIONS]

Common parameters (Table 2‑12):

ParameterPurpose
-aShow all sockets (listening + non‑listening)
-pInclude the owning process
-tShow TCP connections
-uShow UDP connections
-nDo not resolve names (show raw IP/port)
-lShow only listening sockets
-iShow interface list
-rShow routing table

Show a detailed snapshot of network state:

root@linuxprobe:~# netstat -a
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 localhost:ipp 0.0.0.0:* LISTEN
tcp6 0 0 localhost:ipp [::]:* LISTEN
tcp6 0 0 [::]:websm [::]:* LISTEN
udp 0 0 linuxprobe.com:bootpc _gateway:bootps ESTABLISHED
udp 0 0 0.0.0.0:39400 0.0.0.0:*
udp 0 0 0.0.0.0:mdns 0.0.0.0:*
udp6 0 0 [::]:47721 [::]:*
udp6 0 0 [::]:mdns [::]:*

List interfaces with -i:

root@linuxprobe:~# netstat -i 
Kernel Interface table
Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
ens160 1500 32543 0 0 0 9508 0 0 0 BMRU
lo 65536 126 0 0 0 126 0 0 0 LRU

  1. history

history prints recently executed shell commands.
Syntax: history [OPTIONS]

By default, Bash shows the most recent ~1000 commands per user on the host (configurable via HISTSIZE in /etc/profile). Use -c to clear the current user’s history. You can re‑run a command by its event number using !N:

root@linuxprobe:~# history
1 ifconfig
2 uname -a
3 cat /etc/redhat-release
4 uptime
5 free -h
6 who
7 last
8 ping -c 192.168.10.10
9 ping -c 192.168.10.20
10 tracepath www.linuxprobe.com
11 netstat -a
12 netstat -i
13 history
root@linuxprobe:~# !3
cat /etc/redhat-release
Red Hat Enterprise Linux release 10

Command history is stored in the user’s home directory under ~/.bash_history (files beginning with a dot are hidden). View it with cat:

root@linuxprobe:~# cat ~/.bash_history

Clear the in‑memory history for the current shell session:

root@linuxprobe:~# history -c

  1. sos

sos collects system configuration and diagnostic information into an archive—useful when working with support.
Syntax: sos [OPTIONS]

Common subcommands (Table 2‑13):

SubcommandPurpose
reportCollect and produce a diagnostic report
cleanObfuscate sensitive data in the report
helpShow detailed help
collectCollect reports from multiple nodes

Example interactive session:

root@linuxprobe:~# sos report
sosreport (version 4.8.2)

This command will collect diagnostic and configuration information from
this Red Hat Enterprise Linux system and installed applications.

An archive containing the collected information will be generated in
/var/tmp/sos.4p3s8647 and may be provided to a Red Hat support
representative.

Any information provided to Red Hat will be treated in accordance with
the published support policies at:

Distribution Website : https://www.redhat.com/
Commercial Support : https://access.redhat.com/

The generated archive may contain data considered sensitive and its
content should be reviewed by the originating organization before being
passed to any third party.

No changes will be made to system configuration.

Press ENTER to continue, or CTRL-C to quit.Press Enter here

Optionally, please enter the case id that you are generating this report for []: Press Enter here
Setting up archive ...
Setting up plugins ...
Creating compressed archive...

Your sosreport has been generated and saved in:
/var/tmp/sosreport-linuxprobe-2025-05-18-xqbxbhp.tar.xz

Size 18.45MiB
Owner root
sha256 16cfa2860460de92daa5923a84e60b4889afe15522fa5c81ee18606e5fd512b0

Please send this file to your support representative.

Tips:
Think of sos as “remote triage.” If you feel unwell, you might first search your symptoms online; if it’s a minor cold, you drink water and rest—no hospital trip needed. For suspected serious issues, you then seek professional help. Likewise, sos gives support engineers a concise snapshot so smaller problems can be solved remotely and bigger ones can be scoped faster.2.6 Text‑Viewing and Processing Commands

2.5 Finding and Locating Files

In everyday Linux administration, locating files is both fundamental and frequent. Before we search, it helps to be clear about the working directory—the place in the filesystem where you are currently “standing.” Because working directories relate to how Linux stores data, we’ll go deep on directory layout and paths in Chapter 6. For now, follow the hands‑on examples; it’s normal not to master everything at once.


  1. pwd

pwd prints your current working directory (print working directory). Run it with no parameters:

root@linuxprobe:~# pwd
/root

  1. cd

cd changes the current working directory (change directory).
Syntax: cd [OPTIONS] [DIRECTORY]

This is one of the most frequently used Linux commands. Use it to jump quickly and flexibly between locations. Beyond ordinary path changes, a few shortcuts are invaluable:

  • cd - returns to the previous directory.
  • cd .. moves up one level (to the parent).
  • cd ~ jumps to the current user’s home directory.
  • cd ~username jumps to another user’s home (if readable).

Change into /etc:

root@linuxprobe:~# cd /etc

Then change into /bin:

root@linuxprobe:/etc# cd /bin

Return to the last directory you were in (back to /etc here):

root@linuxprobe:/bin# cd -
/etc
root@linuxprobe:/etc#

Jump to your home directory:

root@linuxprobe:/etc# cd ~
root@linuxprobe:~#

Tips:
Your prompt reflects where you are. For example, root@linuxprobe:/etc# indicates you are currently in /etc.


  1. ls

ls lists directory contents (list).
Syntax: ls [OPTIONS] [FILE]

Different working directories show different files. -a shows all entries (including dot‑files); -l shows long details (type, permissions, owner, size, time). Combine them (-al) to see everything with attributes:

root@linuxprobe:~# ls -al
total 40
dr-xr-x---. 15 root root 4096 May 18 09:37 .
dr-xr-xr-x. 18 root root 235 Mar 8 20:02 ..
-rw-r--r--. 1 root root 769 Mar 10 20:04 1.txt
-rw-------. 1 root root 1019 Mar 8 20:06 anaconda-ks.cfg
-rw-------. 1 root root 652 May 18 09:32 .bash_history
-rw-r--r--. 1 root root 18 Jun 24 2024 .bash_logout
-rw-r--r--. 1 root root 141 Jun 24 2024 .bash_profile
-rw-r--r--. 1 root root 429 Jun 24 2024 .bashrc
drwx------. 8 root root 117 Mar 10 20:01 .cache
drwx------. 11 root root 4096 May 18 09:47 .config
…output omitted…

To view directory metadata itself (instead of its contents), add -d:

root@linuxprobe:~# ls -ld /etc
drwxr-xr-x. 134 root root 8192 May 18 09:33 /etc

  1. tree

tree prints directory contents as a hierarchical tree. Run it in any directory to see nested structure at a glance—handy when ls feels too flat.

Compare the two:

Use ls to see just the immediate entries:

root@linuxprobe:~# ls
A Desktop Downloads Pictures Templates
anaconda-ks.cfg Documents Music Public Videos

Use tree to see the hierarchy:

root@linuxprobe:~# tree
.
├── A
│   └── B
│   └── C
├── anaconda-ks.cfg
├── Desktop
├── Documents
├── Downloads
├── Music
├── Pictures
├── Public
├── Templates
└── Videos

12 directories, 1 file

  1. find

find searches for files and directories based on flexible criteria.
Syntax: find [PATH] [TESTS and ACTIONS]

Linux often says “everything is a file,” and find is how you find them. Search predicates cover names, sizes, timestamps, permissions, ownership, and types; matching entries are printed by default.

Table 2‑14. Common find predicates

PredicatePurpose
-name PATTERNMatch name (supports shell globs)
-perm MODEExact permission bits match
-perm -MODEFile has all bits in MODE set
-perm /MODEFile has any bits in MODE set (older GNU syntax +MODE is deprecated)
-user USEROwned by user
-group GROUPOwned by group
-mtime -n/+nContent modified within/ more than n days ago
-atime -n/+nLast accessed within / more than n days
-ctime -n/+nMetadata (permissions/owner) changed within / more than n days
-nouserNo valid owner
-nogroupNo valid group
-newer f1 ! -newer f2Newer than f1 but not newer than f2
-type b/d/c/p/l/fType is block/dir/char/pipe/link/regular
-size NSize test (e.g., +50k)
-prunePrune (skip) a directory
-exec CMD {} \;For each match, run CMD with {} substituted as the path; end the command with \;

Search all configuration files under /etc whose names start with host:

root@linuxprobe:~# find /etc -name "host*"
/etc/nvme/hostnqn
/etc/nvme/hostid
/etc/host.conf
/etc/hosts
/etc/avahi/hosts
/etc/hostname

List every file in the entire system that has the SUID bit set (see Chapter 5):

root@linuxprobe:~# find / -perm -4000
/usr/bin/umount
/usr/bin/chage
/usr/bin/gpasswd
/usr/bin/newgrp
/usr/bin/passwd
/usr/bin/mount
/usr/bin/fusermount3
…output omitted…

Advanced exercise
Find every file owned by user linuxprobe across the entire filesystem and copy them (preserving attributes) into /root/findresults:

root@linuxprobe:~# mkdir /root/findresults
root@linuxprobe:~# find / -user linuxprobe -exec cp -a {} /root/findresults \;

Here, {} stands for each matched file, and the action must end with \; to terminate the -exec clause.


  1. locate

locate rapidly finds paths by name using a prebuilt index.
Syntax: locate [OPTIONS] PATTERN

A full‑disk find is accurate but can be slow. When you only need to look up common files by name, locate is much faster. First, build the index with updatedb. On modern systems the database is typically stored at /var/lib/plocate/plocate.db.

Initialize the index, then verify it exists:

root@linuxprobe:~# updatedb 
root@linuxprobe:~# ls -l /var/lib/plocate/plocate.db
-rw-r-----. 1 root plocate 2527288 May 18 10:25 /var/lib/plocate/plocate.db

Search for anything whose name includes whereis:

root@linuxprobe:~# locate whereis
/usr/bin/whereis
/usr/share/bash-completion/completions/whereis
/usr/share/man/man1/whereis.1.gz

  1. whereis

whereis locates the binary, source, and manual for a given command.
Syntax: whereis COMMAND

Like locate, whereis consults the system’s file indexes, but it focuses specifically on command files and their documentation rather than arbitrary same‑named files.

Find the locations of ls and pwd:

root@linuxprobe:~# whereis ls
ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz
root@linuxprobe:~# whereis pwd
pwd: /usr/bin/pwd /usr/share/man/man1/pwd.1.gz

  1. which

which shows where a command will be resolved in your PATH.
Syntax:** which COMMAND

Unlike whereis, which answers the narrower question “Which executable will the shell run if I type this command right now?” It inspects the directories listed in the PATH environment variable, in order.

Look up the paths for locate and whereis:

root@linuxprobe:~# which locate
/usr/bin/locate
root@linuxprobe:~# which whereis
/usr/bin/whereis

2.6 Viewing and Working with Text Files

By now you’ve learned how to switch working directories and manage files. In Linux, everything is a file—which means configuring services is, at its core, about reading and editing configuration files. If you can’t read those files comfortably, later work will be painful. This section introduces commands for viewing and extracting text, while full‑featured editors are covered in Chapter 4 alongside Shell scripting.

Chapter style
For each tool you’ll get a clear purpose, essential syntax, and real, screen‑accurate examples. Complex editors (e.g., vim, nano) come later; focus here on fast, reliable reading and extraction.


  1. cat

cat prints the content of (typically small) plain‑text files; its name comes from concatenate.
Syntax: cat [OPTIONS] FILE

To include line numbers, add -n:

root@linuxprobe:~# cat -n anaconda-ks.cfg 
1 # Generated by Anaconda 40.22.3.12
2 # Generated by pykickstart v3.52.5
3 #version=RHEL10
4 # Use graphical install
5 graphical
6
7 %addon com_redhat_kdump --disable
8
9 %end
…output omitted…

  1. more

more paginates longer text so the screen doesn’t scroll past what you need.
Syntax: more [OPTIONS] FILE

Press Space to advance a page, Enter for one line, and q to quit. The bottom line shows a percentage to indicate how far you’ve read.

root@linuxprobe:~# more anaconda-ks.cfg 
# Generated by Anaconda 40.22.3.12
# Generated by pykickstart v3.52.5
#version=RHEL10
# Use graphical install
graphical

%addon com_redhat_kdump --disable

%end
…output omitted…
--More--(48%)

  1. head

head prints the first N lines of a file (default 10).
Syntax: head [OPTIONS] FILE

root@linuxprobe:~# head -n 10 anaconda-ks.cfg 
# Generated by Anaconda 40.22.3.12
# Generated by pykickstart v3.52.5
#version=RHEL10
# Use graphical install
graphical

%addon com_redhat_kdump --disable

%end

  1. tail

tail prints the last N lines of a file or follows a file as it grows.
Syntax: tail [OPTIONS] FILE

Last 10 lines:

root@linuxprobe:~# tail -n 10 anaconda-ks.cfg 
autopart
# Partition clearing information
clearpart --none --initlabel

# System timezone
timezone Asia/Shanghai --utc

# Root password
rootpw --iscrypted --allow-ssh $y$j9T$9ksHS/agdH0v1Da0mwbUp6Kg$G.cHNWJ1EJEaBWJxwahrFRlQkqRs82A0ajf32ZTB.PB
user --groups=wheel --name=linuxprobe --password=$y$j9T$nv/rjZ.6xpHhLADJDvIa3uGH$f623oMdVJdxy/QygxwnuZc0FsAdcj8amW9

Follow the newest lines of a log (updates live until you press Ctrl+C):

root@linuxprobe:~# tail -f /var/log/messages
May 18 10:28:07 linuxprobe systemd[1]: packagekit.service: Deactivated successfully.
May 18 10:28:43 linuxprobe systemd[1]: Starting packagekit.service - PackageKit Daemon...
May 18 10:28:43 linuxprobe packagekitd[9218]: g_path_get_basename: assertion 'file_name != NULL' failed
May 18 10:28:43 linuxprobe systemd[1]: Started packagekit.service - PackageKit Daemon.
May 18 10:28:43 linuxprobe packagekitd[9218]: Skipping refresh of media: Cannot update read-only repo
May 18 10:29:13 linuxprobe ptyxis[2945]: context mismatch in svga_surface_destroy
May 18 10:29:13 linuxprobe ptyxis[2945]: context mismatch in svga_surface_destroy
May 18 10:29:13 linuxprobe ptyxis[2945]: context mismatch in svga_surface_destroy

  1. tr

tr translates characters—e.g., switch case, delete characters, or compress repeats. It reads from stdin and writes to stdout, so it’s commonly used in pipelines.
Syntax: tr SET1 SET2

Convert all lowercase letters to uppercase:

root@linuxprobe:~# cat anaconda-ks.cfg | tr 'a-z' 'A-Z'
# GENERATED BY ANACONDA 40.22.3.12
# GENERATED BY PYKICKSTART V3.52.5
#VERSION=RHEL10
# USE GRAPHICAL INSTALL
GRAPHICAL
…output omitted…

  1. wc

wc counts lines, words, and bytes.
Syntax: wc [OPTIONS] FILE

Table 2‑15. wc parameters

ParameterMeaning
-lShow lines only
-wShow words only
-cShow bytes only

Count the number of users (lines) in /etc/passwd:

root@linuxprobe:~# wc -l /etc/passwd
38 /etc/passwd

  1. stat

stat shows a file’s storage details and timestamps (atime/mtime/ctime/birth).
Syntax: stat FILE

  • Access time (atime): last read.
  • Modify time (mtime): last content change.
  • Change time (ctime): last metadata change (permissions/owner).
  • Birth: creation time (if the filesystem records it).
root@linuxprobe:~# stat anaconda-ks.cfg
File: anaconda-ks.cfg
Size: 1019 Blocks: 8 IO Block: 4096 regular file
Device: 253,0 Inode: 33826925 Links: 1
Access: (0600/-rw-------) Uid: ( 0/ root) Gid: ( 0/ root)
Context: system_u:object_r:admin_home_t:s0
Access: 2025-05-18 10:05:30.651095368 +0800
Modify: 2025-03-08 20:06:44.282103236 +0800
Change: 2025-03-08 20:06:44.282103236 +0800
Birth: 2025-03-08 20:06:44.235103234 +0800

  1. grep

grep searches text by string or regular expression and prints matching lines.
Syntax: grep [OPTIONS] PATTERN FILE

While grep has many parameters, two are enough for most day‑to‑day work:

  • -n — show matching line numbers
  • -v — invert the match (show non‑matching lines)

Table 2‑16. Common grep parameters

ParameterMeaning
-bTreat binary files as text
-cShow count of matching lines only
-iCase‑insensitive match
-nShow line numbers
-vInvert the match (show lines without the pattern)

List users who cannot log in (their shell is /sbin/nologin):

root@linuxprobe:~# grep /sbin/nologin /etc/passwd
bin:x:1:1:bin:/bin:/usr/sbin/nologin
daemon:x:2:2:daemon:/sbin:/usr/sbin/nologin
adm:x:3:4:adm:/var/adm:/usr/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/usr/sbin/nologin
operator:x:11:0:operator:/root:/usr/sbin/nologin
games:x:12:100:games:/usr/games:/usr/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/usr/sbin/nologin
…output omitted…

  1. cut

cut extracts columns (fields) from each line of text.
Syntax: cut [OPTIONS] FILE

In /etc/passwd, fields are separated by colons. Show the first field (usernames) by setting the delimiter and field index:

root@linuxprobe:~# head -n 2 /etc/passwd 
root:x:0:0:Super User:/root:/bin/bash
bin:x:1:1:bin:/bin:/usr/sbin/nologin

root@linuxprobe:~# cut -d : -f 1 /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
…output omitted…

  1. diff

diff compares files and shows exact differences.
Syntax: diff [OPTIONS] FILE_A FILE_B

  • --brief — just tell me whether they differ
  • -c — show a detailed, context‑style diff
root@linuxprobe:~# cat diff_A.txt
Welcome to linuxprobe.com
Red Hat certified
Free Linux Lessons
Professional guidance
Linux Course

root@linuxprobe:~# cat diff_B.txt
Welcome tooo linuxprobe.com

Red Hat certified
Free Linux LeSSonS
////////.....////////
Professional guidance
Linux Course
root@linuxprobe:~# diff --brief diff_A.txt diff_B.txt
Files diff_A.txt and diff_B.txt differ
root@linuxprobe:~# diff -c diff_A.txt diff_B.txt
*** diff_A.txt 2025-05-18 10:34:30.829180338 +0800
--- diff_B.txt 2025-05-18 10:34:40.334180802 +0800
***************
*** 1,5 ****
! Welcome to linuxprobe.com
Red Hat certified
! Free Linux Lessons
Professional guidance
Linux Course
--- 1,7 ----
! Welcome tooo linuxprobe.com
!
Red Hat certified
! Free Linux LeSSonS
! ////////.....////////
Professional guidance
Linux Course

  1. uniq

uniq removes adjacent duplicate lines (only consecutive duplicates are collapsed).
Syntax: uniq [OPTIONS] FILE

root@linuxprobe:~# cat uniq.txt 
Welcome to linuxprobe.com
Welcome to linuxprobe.com
Welcome to linuxprobe.com
Welcome to linuxprobe.com
Red Hat certified
Free Linux Lessons
Professional guidance
Linux Course

root@linuxprobe:~# uniq uniq.txt
Welcome to linuxprobe.com
Red Hat certified
Free Linux Lessons
Professional guidance
Linux Course

  1. sort

sort orders lines of text and can also deduplicate.
Syntax: sort [OPTIONS] FILE

Table 2‑17. sort parameters

ParameterMeaning
-fIgnore case
-bIgnore leading blanks
-nNumeric sort
-rReverse order
-uUnique (deduplicate)
-tField delimiter
-kField (or field range) key

Alphabetical sort:

root@linuxprobe:~# cat fruit.txt 
banana
pear
apple
orange
raspberry

root@linuxprobe:~# sort fruit.txt
apple
banana
orange
pear
raspberry

Deduplicate regardless of adjacency:

root@linuxprobe:~# cat sort.txt 
Welcome to linuxprobe.com
Red Hat certified
Welcome to linuxprobe.com
Free Linux Lessons
Linux Course

root@linuxprobe:~# sort -u sort.txt
Free Linux Lessons
Linux Course
Red Hat certified
Welcome to linuxprobe.com

Numeric sort (no “1 comes before 20” mistakes):

root@linuxprobe:~# cat number.txt 
45
12
3
98
82
67
24
56
9

root@linuxprobe:~# sort -n number.txt
3
9
12
24
45
56
67
82
98

Sort structured fields (colon‑delimited), by the 3rd field numerically:

root@linuxprobe:~# cat user.txt 
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon
polkitd:x:998:996:User for polkitd
geoclue:x:997:995:User for geoclue
rtkit:x:172:172:RealtimeKit
pulse:x:171:171:PulseAudio System Daemon
qemu:x:107:107:qemu user
usbmuxd:x:113:113:usbmuxd user
unbound:x:996:991:Unbound DNS resolver
rpc:x:32:32:Rpcbind Daemon
gluster:x:995:990:GlusterFS daemons

root@linuxprobe:~# sort -t : -k 3 -n user.txt
rpc:x:32:32:Rpcbind Daemon
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon
qemu:x:107:107:qemu user
usbmuxd:x:113:113:usbmuxd user
pulse:x:171:171:PulseAudio System Daemon
rtkit:x:172:172:RealtimeKit
gluster:x:995:990:GlusterFS daemons
unbound:x:996:991:Unbound DNS resolver
geoclue:x:997:995:User for geoclue
polkitd:x:998:996:User for polkitd

Summary
Use cat, more, head, and tail to read files efficiently; tr, wc, grep, cut, and diff to transform, count, search, extract, and compare; and uniq/sort to deduplicate and order results. Mastery of these small tools will make you dramatically faster before you ever open a full editor.

2.7 File and Directory Management Commands

Up to this point, your journey through Linux commands has been like pouring a solid foundation. The tower isn’t visibly high yet, but your core skills are already strong. With that groundwork in place, this section introduces the most commonly used day‑to‑day commands for managing files and directories—creating, editing timestamps, copying, moving/renaming, and deleting. You’ll also learn to identify file types, create large files for testing, and archive/extract trees efficiently.

Book context
This section of Learn Linux the Right Way focuses on practical, reproducible steps. Wherever possible, examples show screen‑accurate output so you can follow along and verify your understanding quickly.


  1. touch

touch creates an empty file or updates file timestamps.
Syntax: touch [OPTIONS] FILE

Creating an empty text file with touch is so common—and so simple—that it barely needs explanation:

root@linuxprobe:~# touch linuxprobe

Beyond that, touch can modify the three standard timestamps: Mtime (content modified), Ctime (metadata changed), and Atime (last access). Key parameters appear in Table 2‑18.

Table 2‑18. touch parameters

ParameterPurpose
-aUpdate Atime only
-mUpdate Mtime only
-dUpdate Atime and Mtime together

First, check a file’s modification time; then append content and check again:

root@linuxprobe:~# ls -l anaconda-ks.cfg
-rw-------. 1 root root 1019 Mar 8 20:06 anaconda-ks.cfg
root@linuxprobe:~# echo "Visit LinuxProbe.com to learn linux" >> anaconda-ks.cfg
root@linuxprobe:~# ls -l anaconda-ks.cfg
-rw-------. 1 root root 1062 May 18 10:38 anaconda-ks.cfg

If you’d rather not reveal that the file was edited, reset its timestamp to an earlier value:

root@linuxprobe:~# touch -d "2025-05-18 15:44" anaconda-ks.cfg 
root@linuxprobe:~# ls -l anaconda-ks.cfg
-rw-------. 1 root root 1062 May 18 2025 anaconda-ks.cfg

  1. mkdir

mkdir creates directories (make directory).
Syntax: mkdir [OPTIONS] DIRECTORY

Besides creating a single directory, -p lets you create nested paths in one go:

root@linuxprobe:~# mkdir linuxprobe
root@linuxprobe:~# cd linuxprobe
root@linuxprobe:~/linuxprobe# mkdir -p a/b/c/d/e
root@linuxprobe:~/linuxprobe# cd a
root@linuxprobe:~/linuxprobe/a# cd b
root@linuxprobe:~/linuxprobe/a/b#

  1. cp

cp copies files or directories (copy).
Syntax: cp [OPTIONS] SOURCE DEST

In Linux there are three common outcomes when you copy:

If DEST is a directory, the SOURCE file is copied into that directory.
If DEST is a file, you are prompted to overwrite it (unless you use -f).
If DEST does not exist, the copy proceeds normally.

When copying a directory, remember -r. Frequently used parameters are listed in Table 2‑19.

Table 2‑19. cp parameters

ParameterPurpose
-pPreserve original attributes
-dIf SOURCE is a symlink, copy the link itself, not the target
-rRecursive copy (needed for directories)
-iPrompt before overwrite
-aArchive mode (roughly -pdr; a convenient all‑in‑one for tree copies)

Create a file, then make a backup copy:

root@linuxprobe:~# touch install.log
root@linuxprobe:~# cp install.log x.log
root@linuxprobe:~# ls
install.log x.log

  1. mv

mv moves or renames files and directories (move).
Syntax: mv [OPTIONS] SOURCE DEST

Unlike copying, moving removes the original by default. Renaming within the same directory is simply a move with a new name:

root@linuxprobe:~# mv x.log linux.log
root@linuxprobe:~# ls
install.log linux.log

  1. rm

rm removes files or directories (remove).
Syntax: rm [OPTIONS] FILE

Linux typically asks for confirmation before destructive actions. Use -f for force (no prompts). To remove a directory, add -r. See Table 2‑20.

Table 2‑20. rm parameters

ParameterPurpose
-fForce deletion
-iPrompt before rm
-rRemove directories
-vVerbose progress

Try deleting the two files created earlier; note the difference with and without -f:

root@linuxprobe:~# rm install.log
rm: remove regular empty file 'install.log'? y
root@linuxprobe:~# rm -f linux.log
root@linuxprobe:~# ls
root@linuxprobe:~#

  1. dd

dd copies or converts data using fixed‑size blocks.
Syntax: dd if=VALUE of=VALUE count=VALUE bs=VALUE

dd is powerful and distinctive. It copies content in blocks of a given size and count; it can also transform data while copying. The special device file /dev/zero provides an infinite stream of zero bytes without taking up disk space itself, making it perfect input when you need to generate files of a specific size. Parameters appear in Table 2‑21.

Table 2‑21. dd parameters

ParameterPurpose
ifInput file/device
ofOutput file/device
bsBlock size
countNumber of blocks to copy

Create a 560 MiB file quickly from /dev/zero:

root@linuxprobe:~# dd if=/dev/zero of=560_file count=1 bs=560M
1+0 records in
1+0 records out
587202560 bytes (587 MB, 560 MiB) copied, 14.7741 s, 39.7 MB/s

Create an ISO image from a CD/DVD device—no third‑party tools required:

root@linuxprobe:~# dd if=/dev/cdrom of=RHEL-server-10.0-x86_64-LinuxProbe.Com.iso
13554816+0 records in
13554816+0 records out
6940065792 bytes (6.9 GB, 6.5 GiB) copied, 131.439 s, 52.8 MB/s

Analogy: block size vs. count
Think of your appetite as a fixed total. The ladle size is bs, and the number of scoops is count. Bigger ladle ⇒ fewer scoops. Both parameters control how much you move; any combination that reaches the desired total works.


  1. file

file identifies a file’s type regardless of its name or suffix.
Syntax: file FILE

Linux treats “everything as a file,” but not everything has a helpful extension. Use file to identify what you’re looking at:

root@linuxprobe:~# file anaconda-ks.cfg 
anaconda-ks.cfg: ASCII text
root@linuxprobe:~# file /dev/sda
/dev/sda: block special (8/0)

Tips:
On Windows, double‑clicking chooses an app based on extensions. On Linux, you usually call a tool directly (e.g., cat to read a text file, bash to run a script), so extensions are optional.


  1. tar

tar archives and optionally compresses files and directories.
Syntax: tar [OPTIONS] [FILE_or_DIR]

Compressed archives are faster to transfer. On Linux you’ll commonly see .tar, .tar.gz (gzip), and .tar.bz2 (bzip2). Don’t be intimidated by the variety—most of them are produced (and extracted) by tar. Popular parameters are summarized in Table 2‑22.

Table 2‑22. tar parameters

ParameterPurpose
-cCreate an archive
-xExtract an archive
-tList archive contents
-zUse gzip for compression/extraction
-jUse bzip2 for compression/extraction
-vVerbose (show progress)
-fArchive file name (must immediately precede the name)
-pPreserve original permissions/attributes
-PPreserve absolute paths
-CChange to a directory before extracting

Notes: -c (create) and -x (extract) are mutually exclusive. Use -z/-j according to the archive’s suffix. For long‑running jobs, -v reassures you that the system is working. -f is special—place it directly before the archive name.

A typical command to create a gzip archive is:

root@linuxprobe:~# tar czvf etc.tar.gz /etc
tar: Removing leading `/' from member names
/etc/
/etc/mtab
/etc/fstab
/etc/crypttab
/etc/lvm/
/etc/lvm/devices/
/etc/lvm/devices/system.devices
/etc/lvm/archive/
…output omitted…

Extract to a target directory (create it first with mkdir):

root@linuxprobe:~# mkdir /root/etc
root@linuxprobe:~# tar xzvf etc.tar.gz -C /root/etc
etc/
etc/mtab
etc/fstab
etc/crypttab
etc/lvm/
etc/lvm/devices/
etc/lvm/devices/system.devices
etc/lvm/archive/
…output omitted…

At this stage, some readers worry that limited English will prevent them from mastering Linux. Don’t. You are learning commands, not vocabulary lists. Even when the spelling is identical, the meaning and usage in Linux are what count. With the right learning materials—like this book—you stand on equal footing with anyone.

Take a short break, then continue with Chapter 3!


Review Questions

  1. What is the most commonly used shell on RHEL 10 and many other Linux systems?
    Answer: The Bash (Bourne‑Again Shell) interpreter.

  2. Why do we add parameters to Linux commands?
    Answer: To make commands behave closer to the user’s real needs.

  3. What separates a command, its parameters, and its operands (targets)?
    Answer: One or more spaces.

  4. Write a command that prints the value of the SHELL variable with echo.
    Answer: echo $SHELL.

  5. How do you terminate a process with PID 5529?
    Answer: kill 5529. If you know the service name, you can also use killall NAME.

  6. When reviewing ifconfig, which four items deserve special attention?
    Answer: Interface name, IP address, MAC address, and RX/TX counters.

  7. With uptime showing 0.91, 0.56, 0.32, which time window had the highest load?
    Answer: The most recent 1‑minute interval.

  8. Besides ordering, what’s another use for the numeric IDs in history output?
    Answer: Re‑execute a past command via !NUMBER, avoiding retyping long commands.

  9. If a file is long, which is better: cat, more, head, or tail?
    Answer: Use more for long files (and cat for short ones).

  10. Which parameter should you add to mkdir when creating nested directories?
    Answer: -p for recursive path creation.