0% found this document useful (0 votes)
47 views41 pages

Introduction to Linux Basics

Linux, announced by Linus Torvalds in 1991, is a free and open-source operating system that has evolved into a dominant platform for various applications, including cloud computing and mobile devices. Key features include its modularity, security, and a variety of distributions such as Debian, Ubuntu, and Red Hat. The document also covers essential Linux commands for file management and navigation within the system.

Uploaded by

Nicoara Marius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views41 pages

Introduction to Linux Basics

Linux, announced by Linus Torvalds in 1991, is a free and open-source operating system that has evolved into a dominant platform for various applications, including cloud computing and mobile devices. Key features include its modularity, security, and a variety of distributions such as Debian, Ubuntu, and Red Hat. The document also covers essential Linux commands for file management and navigation within the system.

Uploaded by

Nicoara Marius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Linux

Birth of Linux

On August 25, 1991, Linus Torvalds announced on the [Link] newsgroup that he
was working on a free operating system for 386(486) AT clones as a hobby. The initial version
(0.01) was released in September 1991. It was a basic, but functional kernel.

In 1992, Torvalds released Linux under the GNU General Public License (GPL), aligning it with
the GNU project's principles and allowing it to be freely used and modified.

Early distributions like Slackware (1993) and Debian (1993) emerged, packaging the Linux
kernel with GNU tools and other software.
Companies like Red Hat (1994) and SUSE (1994) began offering commercial distributions,
providing support and services.

2010s:

Linux became the foundation of Android, the world's most widely used mobile operating
system.
Cloud and Data Centers: Linux became the dominant OS for cloud computing, with platforms
like AWS, Google Cloud, and Azure heavily relying on Linux.
Containers: Technologies like Docker and Kubernetes, which are based on Linux,
revolutionized software deployment and orchestration.

Key Features and Principles

Open Source: Linux is free and open-source software, meaning its source code is available
for anyone to view, modify, and distribute.
Modularity: Linux's modular architecture allows for customization and optimization for various
uses, from small embedded systems to large supercomputers.
Security: Linux's design principles and the open-source nature contribute to its security and
robustness.

Major Linux Distributions

●​ Debian:Known for its stability and extensive software repository.


●​ Ubuntu: A user-friendly distribution based on Debian, popular on desktops and servers.
●​ Fedora:Sponsored by Red Hat, focuses on innovation and new technologies.
●​ Red Hat Enterprise Linux (RHEL): Widely used in enterprise environments, known for
its support and stability.
●​ SUSE Linux Enterprise:Another enterprise-focused distribution, known for its
robustness and scalability.
●​ Arch Linux: Known for its simplicity and customization, targeting advanced users.

Linux Filesystem Directories


In Linux, everything is a file. The Linux system has files contained within directories. Programs,
services, texts, and images are all files. Input and output devices are files according to the
system.

/bin Stands for binaries, it contains tools like ls, cp, etc

/boot It contains the bootloader and other boot files.

/dev It stands for device, all physical devices such as USB drive,
etc are mounted here.

/etc Stands for et Cetera, it contains configuration files and


databases.
/home It contains the user’s home directory and files.

Lib Libraries of installed packages located in this directory.

/media It is the default mount point for removable devices such as


media players, USB sticks, etc.

/mnt Stands for mount, this is a temporary mount point for regular
filesystem or empty directories.

/opt Contains locally installed software, optional software such as


vendor-supplied application programs should be located here.

/proc Everything in Linux is considered a file. proc


filesystem(procfs) is a virtual filesystem that displays the
information of the process as a file.

/root This is the home directory of the root user.

/sbin It stands for system binaries, like /bin it also stores binaries
but these binaries are only for root user

/srv It contains server data, This holds site-specific data that is to


be served by the system for protocols such as ftp, rsync,
www, etc.

/sys In some Linux distributions this directory contains sysfs a


virtual filesystem that stores the information related to os and
hardware.

/tmp A place to store temporary files, system clear these files upon
startup.

/usr All the binaries, documentation, libraries, and header files for
all the user applications are stored here.

/var Stands for variables, the value of these changes whenever


the system runs it includes log files, backup, mail, cache, etc.
Essential Linux commands for navigating and managing a Linux
system

File and Directory Management

1. The ls command in Linux is used to list directory contents. It provides information about files
and directories within the file system. The command has several options and flags that modify
its behavior to display various types of information.

●​ ls ​ Basic Command
●​ ls -l​ Long Listing Format, displays detailed information about files and directories,
such as permissions, number of links, owner, group, size, and modification date.

●​ ls -a​ Lists all files, including hidden files (those starting with a dot `.`).
●​ ls -la​ Long Listing with Hidden Files
●​ ls -R​ Lists directories and their contents recursively.
●​ ls -lh​ Displays file sizes in a human-readable format (e.g., KB, MB).
●​ ls -lt​ Sorts files by modification time, newest first

2. The cd command in Linux is used to change the current working directory. Here’s a detailed
look at its usage
●​ cd [directory] directory: The path to the directory you want to navigate to.
●​ cd /path/to/directory Change to a Specific Directory
●​ cd .. ​ Moves up one directory level.

3. The pwd command in Linux stands for "print working directory." It is used to display the
current working directory path.
●​ pwd This command will display the full path to the current directory you are in

4. The mkdir command in Linux is used to create directories.


●​ mkdir directory_name Create a Single Directory
●​ mkdir dir1 dir2 dir3 ​Create Multiple Directories
●​ mkdir -p /path/to/new_directory​ This option allows you to create a directory and any
necessary parent directories that do not already exist.
●​ mkdir -m 755 new_directory​ This option allows you to set the file permissions for
the new directory using the same syntax as the `chmod` command (permissions will
be explained later)
5. The rmdir command in Linux is used to remove empty directories. It cannot remove
directories that contain files or other directories.
●​ rmdir directory_name​ Remove a Single Empty Directory
●​ rmdir -p parent/empty_directory​ This option allows you to remove a directory and its
parent directories if they are empty
●​ rmdir /root/some_directory ​ If you try to remove a directory for which you do not
have the necessary permissions, you will receive a permission denied error

Directory Not Empty: If you try to remove a directory that contains files or other directories,
you will receive an error.

6. The rm command in Linux is used to remove files or directories from the file system.

Be Cautious! The rm command permanently deletes files and directories. There's no built-in
undo or recovery feature, so use it carefully, especially with options like -f and -r

●​ rm [Link] Remove a single file


●​ rm [Link] [Link] [Link] Remove multiple files
●​ rm -r my_directory/ Remove a directory and its contents recursively
●​ rm -f [Link] Force removal of files without prompting
●​ rm -i [Link] Interactively remove a file (prompts for confirmation)

7. The cp command in Linux is used to copy files and directories from one location to another
●​ cp [options] source destination
●​ cp [Link] [Link] Copy a file to another file
●​ cp [Link] /path/to/destination/ Copy a file to another directory
●​ cp [Link] [Link] [Link] /path/to/destination/ Copy multiple files to another
directory
●​ cp -r source_directory/ /path/to/destination/ Copy a directory and its contents to
another directory
●​ cp -i [Link] /path/to/destination/ Copy files interactively (prompts before
overwriting)
●​ cp -p [Link] /path/to/destination/ Copy files while preserving their attributes
!!! By default, if a file with the same name already exists in the destination, cp will overwrite it
without warning. Use the -i option to prevent accidental overwrites.

8. The mv command in Linux is used to move or rename files and directories. It can be used to
move a file or directory from one location to another or to rename a file or directory without
changing its location.

●​ mv [options] source destination


●​ mv old_name.txt new_name.txt Rename a file
●​ mv [Link] /path/to/destination/new_name.txt Move and rename a file in one
command
●​ mv [Link] /path/to/destination/ Move a file to another directory
●​ mv [Link] [Link] /path/to/destination/ Move multiple files to a directory

9. The touch command in Linux is used to create empty files or update the timestamps of
existing files without altering their content. It's a simple yet versatile command that's useful in
various scenarios.

●​ touch [Link] If the specified file does not exist, touch will create an empty file.
●​ touch [Link] [Link] [Link] You can create multiple files at once by specifying
multiple filenames
●​ touch -c non_existent_file.txt Use the -c option if you only want to update the
timestamp of existing files and avoid creating new ones.

EXERCISE

1.​ Start a new terminal


2.​ Run the command ls in your home directory
3.​ Now, run the command ls /bin
4.​ Now the command ls -l /bin (that is, the ls command with the -l option)
5.​ pwd Print the current directory
6.​ cd / ​ Change to the root directory
7.​ cd /home Change to the home directory
8.​ cd ~ Go to your home directory
9.​ cd .. Go up one directory level
10.​cd - Go back to the previous directory
11.​Clear your screen

EXERCISE
1.​ Start a new terminal
2.​ touch [Link] ​​ Create an empty file
3.​ mkdir my_directory ​ Create a new directory
4.​ cp [Link] my_directory/ ​ Copy file to the directory
5.​ mv [Link] [Link] ​ Rename the file
6.​ mv [Link] my_directory/ ​ Move file to a directory
7.​ rm my_directory/[Link] ​ Remove the file
8.​ rmdir my_directory ​ Remove the empty directory
9.​ rm -r my_directory/ ​ Remove directory and its contents
10.​Clear your screen

Review Questions:

1) What Linux command is used to know on which directory are you working
currently?
a) dir
b) prompt
c) who
d) pwd
e) cd

2) You are currently in the directory /home/you/project101/sources and


want to go to the /home directory. What command allows you to go there?:
a) pwd
b) cd home
c) cd ../../..
d) pwd /home
e) cd ../..
f) none of the above

3) What is the purpose of the /bin directory?


a) it contains the files needed to access devices such as printers and disk
drives
b) it contains the administration commands and configuration files, in binary
format
c) it is used by regular users to keep temporary files (recycle bin)
d) there is no such directory in a standard Linux filesystem
e) none of the above
4) What Linux command is used to delete files?
a) del
b) delete
c) remove
d) mv
e) none of the above

5) What Linux command(s) can be used to see the inside of a file (that is, to show
the contents of the file)? (select ALL that apply)
a) ls -l file
b) cat file
c) more file
d) less file
e) view file

File Viewing and Editing

10. The cat command in Linux is used to concatenate and display the content of files. It's one
of the most commonly used commands for viewing file contents in the terminal.

●​ cat [options] file_name


●​ cat [Link] ​ ​ ​ Displaying File Contents
●​ cat -n [Link] ​ ​ Viewing a File with Line Numbers
●​ cat [Link] [Link] > [Link] Concatenating and Redirecting to a File
●​ cat [Link] >> [Link] ​ Append the contents of `[Link]` to `[Link]
●​ cat -s [Link] ​ ​ Remove consecutive empty lines from the output
●​ cat -T -E [Link] ​ ​ Displaying Tabs and Line Endings

For very large files, consider using less or more instead of cat, as they allow you to scroll
through the file without loading the entire content into memory at once

11. The more command in Linux is used to view the content of a file one screen at a time. It’s
particularly useful for reading long files that don’t fit on a single screen, as it allows you to scroll
through the content interactively.

●​ more [options] file_name ​Basic Syntax


●​ more [Link] ​ ​ Viewing a File Page by Page
Scrolling Through a File**
- After opening a file with more, you can navigate through the content using the following
keys:
- Spacebar: Move to the next page.
- Enter: Move one line down.
- b: Move one page back.
- q: Quit more and return to the command prompt.

●​ more +50 [Link] ​ To start viewing a file from line 50


●​ ls -l /usr/bin | more ​​ You can use more to view the output of another command
that produces a lot of text
12. The less command in Linux is a pager program used to view the content of files one
screen at a time. It provides more advanced features compared to more, including the ability
to scroll backward and search through the file.

●​ less [options] file_name


●​ less [Link] To open and view a file with less

Navigating the File use the following keys for navigation:


- Spacebar: Move to the next page.
- Enter: Move one line down.
- b: Move one page back.
- d: Move half a page down.
- u: Move half a page up.
- g: Go to the beginning of the file.
- G: Go to the end of the file.
- /pattern: Search forward for the pattern.
- ?pattern: Search backward for the pattern.
- n: Repeat the search in the forward direction.
- N: Repeat the search in the backward direction.
- q: Quit less and return to the command prompt.

●​ less -N [Link]​ ​ ​ Viewing Line Numbers


●​ less -S [Link]​ ​ ​ Preventing Line Wrapping
●​ less -p "pattern" [Link]​ ​ Starting at a Pattern
●​ less -F [Link]​ ​ ​ Viewing File with Automatic Exit if Fits
●​ ls -l /usr/bin | less ​​ ​ You can use less with pipes to view the output of
other commands
13. The head command in Linux is used to display the beginning portion of a file. By default, it
shows the first 10 lines of the file, but this can be customized with various options. It’s useful
for quickly inspecting the start of a file or viewing the initial lines of large files.

●​ head [options] file_name Basic Syntax


●​ head [Link] ​ ​ Show the First 10 Lines of a File
●​ head -n 20 [Link] ​​ Show the First 20 Lines of a File
●​ head -c 100 [Link] ​ Show the First 100 Bytes of a File
●​ head [Link] [Link] ​ Show the First 10 Lines of Multiple Files
●​ dmesg | head ​ ​ You can use head with pipes to view the beginning of the
output from other commands
14. The tail command in Linux is used to display the end portion of a file or the output from
another command. By default, it shows the last 10 lines of a file, but you can customize this
with various options. It's particularly useful for monitoring log files or viewing recent data.

●​ tail [options] file_name ​ ​ Basic Syntax


●​ tail [Link] ​ ​ ​ ​ Show the Last 10 Lines of a File
●​ tail -n 20 [Link] ​ ​ ​ Show the Last 20 Lines of a File
●​ tail -c 100 [Link] ​ ​ ​ Show the Last 100 Bytes of a File
●​ tail -f /var/log/syslog ​ ​ Monitor a Log File for New Entries
●​ tail -f /var/log/syslog /var/log/[Link] ​ Monitor Multiple Log Files
●​ tail -F /var/log/syslog ​ ​ Handle File Rotation

The tail command is a powerful tool for examining the end of files and monitoring real-time
changes, making it invaluable for system administration and debugging tasks.

[Link] (Vi IMproved) is a powerful and versatile text editor in Linux, an enhanced version of
the vi editor. It's widely used for editing configuration files, writing scripts, and programming.
vim provides a range of features including syntax highlighting, multiple modes, and extensive
customization.

Basic Modes in vim

1. Normal Mode (Default Mode) - Used for navigation and manipulating text. You start in this
mode when you open a file.
2. Insert Mode - Used for inserting text. Enter this mode by pressing i from Normal mode.
3. Visual Mode - Used for selecting text. Enter this mode by pressing v from Normal mode.
4. Command-Line Mode - Used for executing commands (e.g., saving, quitting). Enter this
mode by pressing : from Normal mode.
●​ vim [Link] ​ ​ Open a File

File Permissions and Ownership

16. The chmod command in Linux is used to change the permissions of files and directories.
Permissions control who can read, write, or execute a file. The command can modify
permissions using symbolic mode or numeric mode.
●​ chmod [options] mode file_name Basic Syntax

Linux file permissions are typically represented in three categories:

1. User (Owner): The file's owner.


2. Group: The group associated with the file.
3. Others: Everyone else.

Permissions are represented as:

- r: Read permission (4)


- w: Write permission (2)
- x: Execute permission (1)

Numeric Mode

Permissions can be set using a three-digit octal number where each digit represents a
category (User, Group, Others). Each digit is a sum of permissions:

- 4: Read
- 2: Write
- 1: Execute
For example:

- 7: Read (4) + Write (2) + Execute (1) = 7


- 6: Read (4) + Write (2) = 6
- 5: Read (4) + Execute (1) = 5

Symbolic Mode

Permissions can be set using symbolic representations:

- r: Read
- w: Write
- x: Execute

Permissions are modified with operators:

+: Add a permission
-: Remove a permission
=: Set exact permissions

For example:

u+r: Add read permission for the user (owner)


g-w: Remove write permission for the group
o=x: Set execute permission only for others
Common Commands

1. Set Permissions Using Numeric Mode

- To set permissions to rwxr-xr-- (User: read, write, execute; Group: read, execute; Others:
read): chmod 754 [Link]

2. Set Permissions Using Symbolic Mode

- To add execute permission for the user: chmod u+x [Link]


- To remove write permission for the group: chmod g-w [Link]
- To set exact permissions rwxr-xr--: chmod u=rwx,g=rx,o=r [Link]

3. Set Permissions Recursively


- To change permissions of all files and directories within a directory:

chmod -R 755 /path/to/directory

4. Change Ownership and Permissions


- To change ownership and permissions together (using `chown`):

chown user: group [Link]


chmod 644 [Link]

Examples

1. Make a File Executable

- To add execute permission for the user: chmod u+x [Link]

2. Remove Write Permission for Group

- To remove write permission for the group: chmod g-w [Link]

3. Set Permissions for a Directory Recursively

- To set permissions for all files and directories within /var/www:

chmod -R 755 /var/www


4. Set Exact Permissions

- To set permissions to rwxr-xr--: chmod 755 [Link]

Practical Tips

- Check Current Permissions: Use ls -l [Link] to view the current permissions of a file.
- Permissions on Directories: For directories, execute permission allows entering the directory,
and write permission allows creating and deleting files within it.
- Symbolic vs. Numeric Mode:Symbolic mode is more descriptive and easier to understand for
specific changes, while numeric mode is more compact and useful for setting permissions
directly.

The chmod command is essential for managing file and directory permissions in Linux,
ensuring appropriate access control and security.

17. The chown command in Linux is used to change the ownership of files and directories. It
allows you to specify a new owner and/or group for a file or directory. This is useful for
managing permissions and access control.

●​ chown [options] new_owner[:new_group] file_name​ ​ Basic Syntax

Key Concepts

- Owner: The user who owns the file.


- Group: The group associated with the file.

You can specify ownership in the following formats:

1. owner: Change only the owner.


2. owner:group: Change both the owner and the group.
3. group: Change only the group (but this is less common).

Common Commands

1. Change the Owner of a File


- To change the owner to username: chown username [Link]

2. Change the Owner and Group of a File

- To change the owner to username and the group to groupname:

chown username:groupname [Link]

3. Change the Group of a File

- To change only the group to groupname (this is less common):

chown :groupname [Link]

4. Change Ownership Recursively

- To change the ownership of a directory and all its contents:

chown -R username:groupname /path/to/directory

5. Change Ownership Using --reference

- To change ownership of a file to match another file’s ownership:

chown --reference=file1 file2

Options

-R: Recursively change ownership of directories and their contents.


chown -R username:groupname /path/to/directory
--reference=file: Use the ownership of the specified file to change the ownership of the target
file.

chown --reference=file1 file2

-v: Verbose mode, showing which files are being changed.

chown -v username:groupname [Link]

Examples
1. Change the Owner of a File

- To change the owner of [Link] to alice: chown alice [Link]

2. Change the Owner and Group of a File

- To change the owner to bob and the group to admins: chown bob:admins [Link]

3. Change the Group of a File

- To change only the group to staff: chown :staff [Link]

4. Change Ownership Recursively

- To change ownership of all files and directories within /var/www:

chown -R www-data:www-data /var/www

5. Change Ownership Using Reference File

- To change ownership of file2 to match file1:

chown --reference=file1 file2

Practical Tips

- Check Current Ownership: Use ls -l [Link] to view the current owner and group of a file.
- Ownership and Permissions:Changing ownership does not alter file permissions; use chmod
for permission changes.

- Permissions: You typically need superuser (root) privileges to change ownership of files that
you do not own. Use sudo if necessary:

sudo chown username:groupname [Link]

The chown command is a crucial tool for managing file ownership and ensuring proper access
control in Linux systems.
System Information and Management

18. The ps command in Linux is used to display information about active processes. It
provides a snapshot of the currently running processes, including details such as process IDs
(PIDs), memory usage, CPU usage, and more. This is useful for monitoring system
performance and managing processes.

●​ ps [options]​ ​ Basic Syntax

Common Options

- ps: By default, ps shows processes running in the current shell session.


- ps aux: Shows a detailed list of all processes running on the system, including processes
from other users.

- a: Show processes for all users.


- u: Show the user/owner of the process.
- x: Show processes not attached to a terminal.

●​ ps aux

- ps -ef: Another common format for displaying all processes. It provides similar information to
ps aux.
- e: Show all processes.
- f: Display a full-format listing.

●​ ps -ef

- ps -e or ps -A: Display all processes. The -A flag is an alternative to -e.

●​ ps -e

- ps -u username: Display processes for a specific user.

●​ ps -u username

- ps -p PID: Display information about a specific process identified by its PID.

●​ ps -p 1234
-ps -l: Display detailed information in long format.

●​ ps -l

-ps -o format: Customize the output format. Replace format with fields like pid, user, cmd, etc.

●​ ps -o pid,user,cmd

Common Fields

When using ps aux or ps -ef, you might see the following fields:

- USER: ​ The user who owns the process.


- PID: ​​ Process ID.
- %CPU: ​ CPU usage percentage.
- %MEM: ​ Memory usage percentage.
- VSZ: ​ Virtual memory size (in KB).
- RSS: ​ Resident Set Size (physical memory used in KB).
- TTY: ​ Terminal associated with the process.
- STAT: ​ Process status (e.g., running, sleeping).
- START: ​ Start time of the process.
- TIME: ​ CPU time used by the process.
- COMMAND: ​ Command used to start the process.

Examples

1. List All Processes


- To list all processes running on the system: ps aux

2. Display Processes for a Specific User


- To show processes for the user john: ps -u john

3. Show Detailed Information for a Specific Process


- To display detailed information for process with PID 1234: ps -p 1234 -f

4. View Processes with Custom Output Format


- To show only the PID and command for each process: ps -eo pid,cmd

5. Find the Process Tree


- To view a process tree (hierarchical view of processes): ps aux --forest

Practical Tips

- Combining with Other Commands: You can use ps in combination with other commands like
grep to filter results. For example, to find processes related to nginx:

ps aux | grep nginx

- Monitoring Processes: For real-time monitoring of processes, you might use top or htop,
which provide a dynamic view of system processes.

- Understanding Process States Familiarize yourself with common process states in the STAT
field, such as R (running), S (sleeping), and Z (zombie).

The ps command is an essential tool for managing and monitoring processes on a Linux
system, providing valuable insights into process behavior and system performance.

[Link] top command in Linux provides a dynamic, real-time view of the system’s resource
usage, including CPU, memory, and processes. It is a powerful tool for monitoring system
performance and diagnosing issues.

●​ top [options]​ ​ Basic Syntax

Overview of top

When you run top, it displays a continuously updating list of processes, sorted by CPU or
memory usage by default. It provides various system metrics and process details.

Main Sections of top Output

1. Summary Area (Top of the Screen)


- System Information: Includes system uptime, number of users, load averages (e.g., 1 min,
5 min, 15 min), and memory usage.
- Task Information: Displays the number of total processes, running processes, sleeping
processes, stopped processes, and zombie processes.

2. Process List Area (Below the Summary Area)


- PID: ​ ​ ​ Process ID.
- USER:​ ​ ​ User who owns the process.
- PR:​ ​ ​ Priority of the process.
- NI:​​ ​ ​ Nice value (priority adjustment).
- VIRT:​ ​ ​ Virtual memory size.
- RES:​ ​ ​ Resident Set Size (physical memory used).
- SHR:​ ​ ​ Shared memory.
- S:​ ​ ​ ​ Process state (e.g., running, sleeping).
- %CPU:​ ​ ​ CPU usage percentage.
- %MEM:​ ​ ​ Memory usage percentage.
- TIME+: ​ ​ ​ Total CPU time used.
- COMMAND:​ ​ Command used to start the process.

Common Commands and Keys in top

- h: Display help menu with key commands.


- q: Quit `top`.
- k: Kill a process. Enter the PID and signal to terminate the process.
- r: Renice a process. Enter the PID and the new nice value to adjust process priority.
- P: Sort processes by CPU usage (default).
- M: Sort processes by memory usage.
- T: Sort processes by runtime.
- 1: Toggle the display of individual CPU cores.
- c: Toggle between displaying the command line and program name.
- s: Change the refresh interval (in seconds).
- u: Filter processes by a specific user.

Customizing top Output

-Specify Output Fields:


- You can customize the display fields using the -o option followed by field names.

top -o %MEM

- Show Only Specific Processes:


- Use the -p option to specify PIDs to display.

top -p 1234,5678

- Run top in Batch Mode:


- For non-interactive output (useful for scripts), use the -b option.

top -b -n 1

Here, -n 1 specifies the number of iterations.

Examples

1. Run top with Default Settings top

2. Sort Processes by Memory Usage


- While the top is running, press M.

3. Filter Processes by User


- Press u, then enter the username to filter processes.

4. Change the Refresh Interval to 5 Seconds


- Whiley he top is running, press s and enter 5.

5. Run top and Output Results to a File


- Use batch mode and redirect output: top -b -n 1 > top_output.txt

Practical Tips

- Monitoring Performance: top is useful for real-time monitoring of system performance,


including CPU and memory usage.

- Performance Analysis: Use the top command to identify processes consuming excessive
resources and troubleshoot performance issues.
- Alternatives: For a more advanced and user-friendly interface, consider using htop, which
offers a similar functionality with a more interactive and graphical interface.

The top command is an essential tool for Linux system administrators and users to monitor
system performance, manage processes, and troubleshoot issues effectively.

20. The df command in Linux is used to display information about disk space usage on the file
system. It provides a quick overview of how much disk space is available, used, and free
across different file systems or mounted partitions.
●​ df [options] [file] ​ Basic Syntax

The output of df typically includes the following columns:

- Filesystem: The name of the file system or partition.


- Size: Total size of the file system.
- Used: Amount of space currently used.
- Avail: Amount of space available for use.
- Use%: Percentage of disk space that is used.
- Mounted on: The mount point, indicating where the file system is mounted in the directory
structure.

●​ df ​ Display Disk Usage for All File Systems


●​ df -h​ Display Disk Usage in Human-Readable Format to see the disk usage with sizes
in KB, MB, or GB
●​ df -T​ Display File System Types to show the file system type (e.g., ext4, xfs, etc.)
●​ df -t ext4​ Display Disk Usage for a Specific File System Type
●​ df -x tmpfs ​ Display Disk Usage Excluding a Specific File System Type
●​ df --total​ Display Disk Usage with Total Summary to include a total line at the end of
the output

Practical Tips

- Monitoring Disk Usage: Use df -h regularly to monitor disk space and prevent running out of
space, especially on critical partitions like /, /home, and /var.

- Troubleshooting: If a system is running out of disk space, df can help identify which partitions
or file systems are full.

- Inode Exhaustion:Running out of inodes can also prevent file creation. Use df -i to check
inode usage, especially on systems with many small files.

- Automated Monitoring: Combine df with scripts to automate disk space monitoring and send
alerts when free space drops below a threshold.

The df command is an essential tool for managing disk space on Linux systems, providing
critical information to ensure that storage resources are used efficiently and that the system
remains operational.
21. The du command in Linux is used to estimate and display the disk space usage of files
and directories. It helps you understand how much space a directory or a file is consuming,
which is useful for managing disk space.

●​ du [options] [file|directory] ​Basic Syntax


●​ du​ Display Disk Usage of the Current Directory and its subdirectories
●​ du -h ​Display Disk Usage in Human-Readable Format to show sizes in KB, MB, or GB
●​ du -sh /path/to/directory​ Display the Total Size of a Directory
●​ du -ah /path/to/directory​ Display Disk Usage for All Files and Directories
●​ du -h --max-depth=1 /path/to/directory ​ Limit Depth of Directory Traversal to show disk
usage for a directory and its immediate subdirectories
●​ du -ch /path/to/directory ​ Display a Grand Total to show the cumulative disk usage
●​ du -h --exclude="*.log" /path/to/directory​ Exclude Specific Files or Directories

Practical Tips

- Identifying Large Directories: Use du -sh * within a directory to quickly identify which
subdirectories or files are using the most space.

- Monitoring Disk Usage: Combine d with sort to find the largest directories:

du -sh * | sort -rh | head -n 10

This command lists the top 10 largest directories or files.

- Using du with Network File Systems: When working with network-mounted file systems, use
the -x option to avoid traversing mounted points.

- Automating Disk Space Checks: Create a script that uses du to monitor disk space usage
and send alerts if certain thresholds are exceeded.

The du command is an essential tool for managing disk space on Linux systems, helping
users and administrators pinpoint where storage is being used and identify potential areas for
cleanup.

22. The free command in Linux is used to display information about the system’s memory
usage. It provides a quick overview of how much physical memory (RAM) and swap space is
available, used, and free.

●​ free [options]​​ Basic Syntax


The output of the free command typically includes several columns:

1. total: Total amount of memory.


2. used: Amount of memory that is currently in use.
3. free: Amount of memory that is not being used at all.
4. shared: Memory used by the `tmpfs` file systems.
5. buff/cache: Memory used by the kernel buffers, page cache, and slabs.
6. available: The amount of memory that is available for starting new applications, without
swapping.

The output also distinguishes between Mem (physical RAM) and Swap (swap space on disk).

●​ free -h​​ Display Memory Usage in Human-Readable Format to view memory


usage with sizes in KB, MB, or GB
●​ free -s 2 ​ Continuously Monitor Memory Usage to monitor memory usage with
updates every 2 seconds
●​ free -m​ Display Memory Usage in Megabytes
●​ free -t​ ​ Show Memory and Swap Totals to include a total line summarizing RAM
and swap space
●​ free -c 3 -s 1 Display Memory Usage for a Specified Number of Updates to display
memory usage three times with a 1-second interval

Understanding the Output

- Physical Memory (Mem): This includes the total physical memory, how much is used, how
much is free, and how much is used for buffers/cache.
- Swap Memory (Swap): This shows the total swap space, how much is used, and how much
is free. Swap is used when physical memory is full, and the system starts swapping data to
disk, which is slower.
- Available Memory: This is an estimate of how much memory is available for starting new
applications without swapping.

Practical Tips

-System Performance Monitoring: The free command is useful for monitoring system
performance, particularly to see if your system is running low on memory or using swap
excessively.
- Understanding Buffers/Cache: The memory reported as used includes buffers and cache,
which are used by the system to optimize performance. The available memory provides a
better estimate of how much memory can be used by new applications.

- Identifying Memory Issues: Regularly checking memory usage with free can help identify
memory leaks or applications consuming too much memory, allowing for timely intervention
before the system starts swapping heavily.

The free command is a straightforward and powerful tool for understanding and monitoring
memory usage on a Linux system, helping to ensure that your system remains responsive and
efficient.

23. The uname command in Linux is used to display system information, including the kernel
name, version, and other details about the system. It’s a simple yet powerful command for
quickly identifying the operating system and kernel version of a system.

●​ uname [options]​ Basic Syntax


●​ uname -a ​ ​ Display All System Information
●​ uname -r ​ ​ Display the Kernel Version
●​ uname -o ​ ​ Display the Operating System name
●​ uname -m ​ ​ Display the Machine Hardware Name to find out the architecture of
the machine (e.g., x86_64)
●​ uname -n​ ​ Display the Hostname

Practical Tips

- Checking Kernel Version: The uname -r command is particularly useful when you need to
know the exact version of the Linux kernel running on your system, such as when installing
kernel modules or troubleshooting compatibility issues.

- Verifying System Architecture:The uname -m option can help verify whether you are running
a 32-bit or 64-bit system, which is important when installing software or operating system
updates.

- System Information in Scripts: The uname command is commonly used in shell scripts to
make decisions based on the system type or kernel version, ensuring that the script behaves
appropriately on different systems.
- Understanding uname -a: The output of uname -a typically includes the kernel name,
hostname, kernel version, date of kernel compilation, architecture, and operating system,
providing a quick summary of key system information.

The uname command is a quick and useful tool for gathering essential system information,
particularly for system administrators and users who need to identify the kernel version,
system architecture, or other key details about their Linux environment.

24. The whoami command in Linux is used to display the username of the current user. It's a
simple and straightforward command that tells you which user account you are currently
operating under.

●​ whoami​ ​ Basic Syntax

- When you type whoami and press Enter, the command outputs the username of the user
who is currently logged in and running the terminal session.
- The whoami command is essentially equivalent to running id -un, which also returns the
username of the current user.

Practical Uses
- Checking User Identity: The whoami command is useful when you need to confirm which
user account is being used, especially when working in a multi-user environment or when
using su or sudo to switch users.

- Scripting: In scripts, whoami can be used to conditionally execute commands based on the
current user. For example, certain commands might only be run if the script is executed by a
specific user.

- Debugging: If you're unsure which user context you're operating in, particularly after switching
users or running commands with elevated privileges, whoami provides a quick way to verify
your current user.

The whoami command is a quick and simple way to verify the user identity in a Linux session,
helping to avoid mistakes related to user permissions and context.

[Link] hostname command in Linux is used to display or set the system's hostname. The
hostname is the name assigned to a computer (or host) on a network and is used to identify
the machine in the network.
●​ hostname [options] [new_hostname] ​ Basic Syntax
●​ hostname ​ Display the Current Hostname of your machine
●​ sudo hostname mynewhost Change the Hostname change the hostname to
mynewhost

- Note:This change will only persist until the system reboots. To make it permanent, you'll
need to edit /etc/hostname and /etc/hosts (in most distributions).

●​ hostname -f ​ Display the Fully Qualified Domain Name (FQDN)


●​ hostname -i ​​ Display the IP Address of the Host
●​ hostname -I​ ​ Display All IP Addresses assigned to the host
●​ hostname -d​​ Display the Domain Name​ of the system
●​ hostname -s​​ Display the Short Hostname without any domain information

Practical Tips

-Network Configuration: The hostname command is commonly used when configuring or


troubleshooting network settings. Knowing or setting the correct hostname is important for
services like DNS, SSH, and others that depend on host identity.
- Temporary vs. Permanent Changes: Changing the hostname with the hostname command
only affects the current session. To make it permanent, you need to modify system files like
/etc/hostname and /etc/hosts.

- Script Usage: In scripts, hostname can be used to make decisions based on the machine's
identity, such as setting specific configurations or logging information.

The hostname command is a versatile tool for managing and querying the system's
hostname, making it essential for network administration and system configuration.

26. The uptime command in Linux is used to display how long the system has been running,
along with the current time, the number of users currently logged in, and the system load
averages for the past 1, 5, and 15 minutes.

●​ uptime [options] ​ Basic Syntax

Output Overview

When you run the uptime command, the output typically includes:

1. Current time: The current system time.


2. Uptime: How long the system has been running since the last reboot.
3. Number of users: The number of users currently logged into the system.
4. Load averages: The system load averages for the past 1, 5, and 15 minutes. These indicate
the average number of processes that are either running or waiting for CPU time.

Practical Tips

- System Health Check: The uptime command is useful for quickly checking how long a
system has been running, which can indicate stability or potential issues after a reboot.

- Monitoring System Load: The load averages give you an idea of how busy your system is. A
load average of 1.0 means the system is fully loaded (i.e., one process is using or waiting for
CPU resources per CPU core). Higher values indicate more load. If the load average is
consistently high, it might indicate that the system is under heavy usage or strain.

- Detecting Reboots: By looking at the uptime, you can determine when the system was last
rebooted, which can be useful for troubleshooting or verifying system stability.
Using uptime with Other Commands

- With watch: You can use watch with uptime to monitor the system's uptime and load
average in real time:

watch uptime

- In Scripts: The uptime command can be used in scripts to log or alert based on system
uptime or load averages, helping automate system monitoring.

The uptime command is a quick and effective tool for getting an overview of system
performance, making it a staple in both casual monitoring and serious system administration
tasks.

Networking

[Link] ping command in Linux is used to test the network connectivity between your system
and another system or device. It sends ICMP (Internet Control Message Protocol) echo
request packets to the target host and listens for echo reply packets to determine if the host is
reachable and how long it takes to respond.

●​ ping [options] <hostname_or_ip_address> ​ Basic Syntax


●​ ping [Link] ​ Ping a Host or IP Address

This command will send ICMP packets to [Link] and display the results until you
stop it with Ctrl+C.

●​ ping -c 4 [Link] Ping with a Specific Number of Packets

This command sends 4 packets and then stops.

●​ ping -w 10 [Link]​ Ping with a Timeout

The -w option allows you to set a timeout, after which the ping command will stop, pinging
after 10 seconds.

●​ ping -s 64 [Link]​ Change the Packet Size

You can specify the size of the packets sent using the -s option.
This command sends packets of 64 bytes in size.

●​ sudo ping -f [Link] Flood Ping

The -f option sends packets as quickly as possible and requires root privileges. This is often
used for stress testing and network diagnostics.

●​ ping -b [Link] ​ Ping a Broadcast Address to send packets to all devices on


a network.

Note that many networks are configured to block broadcast pings for security reasons.

●​ ping -i 2 [Link]​ Limit Time Between Pings

Use the -i option to set the interval between sending packets (in seconds).

This command sends a packet every 2 seconds.

Practical Tips

- Network Troubleshooting: ping is a fundamental tool for diagnosing network issues. If you
can't reach a website, you can use ping to see if the problem is with network connectivity.
- Measuring Latency: The time value in the ping output gives you an idea of the latency (delay)
between your machine and the target. Higher times can indicate network congestion or other
issues.

- Checking Host Availability: You can use ping to see if a particular host (such as a server or
another computer) is up and running.

- Testing Network Configuration: After configuring network settings, ping can be used to verify
that your machine can communicate with other machines on the network.

- Script Usage: ping can be integrated into scripts for automated network monitoring, alerting
you when a host becomes unreachable.

The ping command is a versatile and essential tool for network administrators and users alike,
offering a simple way to check connectivity, diagnose issues, and measure network
performance.

[Link] Linux, both ifconfig and ip commands are used to manage network interfaces, but ip is
the more modern and powerful tool, and it’s recommended over ifconfig in most cases. Here’s
a comparison and explanation of each

●​ ifconfig ​ Basic Usage view Network Interface Information


●​ sudo ifconfig eth0 up Bring an Interface Up
●​ sudo ifconfig eth0 down Bring an Interface Down
●​ sudo ifconfig eth0 [Link] netmask [Link] Assign an IP Address

●​ ip addr show Basic Usage view Network Interface Information


●​ ip a Basic Usage view Network Interface Information
●​ sudo ip link set eth0 up Bring an Interface Up
●​ sudo ip link set eth0 down Bring an Interface Down
●​ sudo ip addr add [Link]/24 dev eth0 Assign an IP Address
●​ sudo ip addr del [Link]/24 dev eth0 Remove an IP Address
●​ ip route show View Routing Table

Why Use ip Over ifconfig?

1. Modern and Actively Maintained: ip is part of the iproute2 package, which is actively
maintained and includes more features for modern networking requirements.
2. More Comprehensive: The ip command covers a broader range of network configuration
tasks, including advanced routing, tunneling, and more.
3. Standardization: Many modern Linux distributions have moved away from ifconfig to ip,
making it the standard tool for network management.

Summary

- Use ifconfig if you are working on older systems where ip might not be available, or if you
are dealing with legacy scripts and tools that still rely on ifconfig.
- Use ip if you are on a modern Linux system and need a more powerful, flexible, and actively
supported tool for managing network interfaces.

For new scripts and tasks, it's generally recommended to use the ip command.

29. The netstat command in Linux is a powerful tool used for network troubleshooting and
monitoring. It provides detailed information about network connections, routing tables, interface
statistics, masquerade connections, and multicast memberships. However, it's worth noting
that netstat is now largely considered deprecated in favor of more modern tools like ss and ip
from the iproute2 package.

●​ netstat -a​ Basic Usage of netstat


●​ netstat -l​ Shows all active network connections, including listening and non-listening
(closed) sockets.
●​ netstat -t​ Lists all listening ports on the system.
●​ netstat -u​ UDP connections
●​ netstat -i​ Display Network Interface Statistics shows a list of network interfaces with
statistics such as the number of received and transmitted packets
●​ netstat -r​ Display Routing Table
●​ netstat -s​ Display Statistics by Protocol provides a summary of statistics for each
protocol (TCP, UDP, ICMP, etc.)
●​ netstat -an​ Display All Ports (Listening and Non-Listening) displays all network
connections with numeric IP addresses and port numbers.
●​ watch netstat -at ​ Monitor Connections in Real-Time

The watch command can be used to monitor the output of netstat in real-time.

Modern Alternatives to netstat


ss Command: The ss command is the modern replacement for netstat and is faster and more
detailed in many cases.

●​ ss -t ​ Display All TCP Connections


●​ ss -l​ List Listening Ports

Summary

- The netstat command is still useful, especially in legacy systems, but for modern systems,
you might want to familiarize yourself with ss and ip commands.
- netstat provides a wide range of options to troubleshoot and monitor network activities, but
it's recommended to transition to ss for better performance and additional features.

30. The scp (Secure Copy Protocol) command in Linux is used to securely transfer files and
directories between two systems over a network. It leverages SSH (Secure Shell) to provide
encrypted file transfers, making it a safer alternative to traditional file transfer methods like cp
(which only works locally) or ftp.

●​ scp [options] source destination ​ Basic Syntax


●​ scp /path/to/local/file username@remote_host:/path/to/remote/directory
This command copy a File from Local to Remote System

Example: scp /home/user/[Link] user@[Link]:/home/user/

●​ scp username@remote_host:/path/to/remote/file /path/to/local/directory


This command copy a File from Remote to Local System

Example: scp user@[Link]:/home/user/[Link] /home/user/

●​ scp username1@remote_host1:/path/to/file
username2@remote_host2:/path/to/destination
This command copy a File Between Two Remote Systems

Example:scp user1@[Link]:/home/user1/[Link] user2@[Link]:/home/user2/

●​ scp -P 2222 /path/to/local/file username@remote_host:/path/to/remote/directory


P port: Specify the port to connect to on the remote host. (Note: it's uppercase P for
scp, lowercase -p is used for preserving file attributes.)
Summary

The scp command is a simple yet powerful tool for secure file transfers between local and
remote systems. It’s a common utility for system administrators and anyone needing to move
files securely across networks.

31. The ssh (Secure Shell) command in Linux is used to securely connect to a remote
machine over a network. It allows users to execute commands, transfer files, and manage
systems remotely with encrypted communication, ensuring privacy and data integrity.

●​ ssh [options] username@hostname​ Basic Syntax


●​ ssh username@remote_host​ ​ Connecting to a Remote Server
Example: ssh user@[Link]

This command connects to the remote machine with IP address [Link] using the
specified user account.

●​ ssh -p port_number username@remote_host Connecting to a Remote Server on a


Specific Port

Example: ssh -p 2222 user@[Link]

This command connects to the remote machine using port 2222 instead of the default SSH
port 22

●​ ssh -i /path/to/private_key username@remote_host Using a Specific Private Key


for Authentication

Example: ssh -i ~/.ssh/id_rsa user@[Link]

This command connects to the remote machine using the specified private key (id_rsa) for
authentication.

●​ ssh username@remote_host 'command' ​ Running a Command on a Remote


Server Without Logging In

Example: ssh user@[Link] ls -l /var/www


This command connects to the remote machine, runs the ls -l /var/www command, and then
disconnects.

●​ ssh -L local_port:destination_host:destination_port username@remote_host


Local Port Forwarding:

Example: ssh -L 8080:localhost:80 user@[Link]

This command forwards connections on port 8080 on the local machine to port 80 on the
remote machine (through the SSH server).

●​ ssh -R remote_port:destination_host:destination_port username@remote_host


Remote Port Forwarding

Example: ssh -R 8080:localhost:3000 user@[Link]

This command forwards connections on port 8080 on the remote machine to port 3000 on the
local machine.

!!! Connect to a Server with a Specific SSH Config:

ssh myserver

If you have a configuration in `~/.ssh/config` like:

Host myserver
HostName [Link]
User user
Port 2222
IdentityFile ~/.ssh/id_rsa

Summary

The ssh command is a versatile and essential tool for securely managing remote systems. It
offers a wide range of functionalities, from simple remote login to complex tunneling, file
transfer, and secure communication.

Package Management (Example with `apt` for Debian-based systems)


32. The apt-get update command in Linux is used to refresh the local package index on a
Debian-based system (such as Ubuntu). This command fetches the latest package lists from
the repositories configured in the system, ensuring that the package manager is aware of the
most recent versions and available updates for installed software.

●​ sudo apt-get update ​ Basic Usage

What Happens When You Run apt-get update?

1. Repository Lists are Refreshed: The command downloads the latest package lists from the
repositories specified in your /etc/apt/[Link] file and any files in the
/etc/apt/[Link].d/ directory.

2. No Actual Packages are Installed or Upgraded: It doesn’t install or upgrade any packages;
it merely updates the local list of available packages and their versions.

3. Prepares the System for Package Management Operations: After running apt-get update,
you can then proceed with commands like apt-get upgrade or apt-get install to actually
upgrade packages or install new ones.

Summary

The apt-get update command is essential for keeping your system's package database up to
date. It's a necessary step before installing new software or performing system upgrades to
ensure that you have access to the latest versions of packages available in your configured
repositories.

[Link] apt-get upgrade command in Linux is used to upgrade all the installed packages on
your system to their latest available versions, as indicated by the package lists retrieved by
apt-get update.

●​ sudo apt-get upgrad​ e​ Basic Usage

What Happens When You Run apt-get upgrade?

1. Compares Installed Packages with Available Updates: The command checks the versions of
installed packages against the versions available in the repositories that were updated using
apt-get update.
2. Upgrades Packages: It upgrades all installed packages to the latest versions available, as
long as no packages need to be removed or new dependencies need to be installed.

3. Prompts for Confirmation:Before proceeding, it will typically display the list of packages that
will be upgraded and ask for your confirmation.

4. No Automatic Removal or Installation of Packages: apt-get upgrade only upgrades


packages that can be upgraded without removing or installing other packages. If a package
upgrade requires removing or installing other packages, `apt-get upgrade` will hold back that
upgrade.

Upgrading the Kernel: apt-get upgrade typically upgrades the Linux kernel if a new version is
available. However, the older kernels are usually not removed automatically, which can lead to
the accumulation of old kernels on your system. You may need to manually remove old kernels
if disk space becomes an issue.

Reboot After Upgrading: After running apt-get upgrade, especially if the kernel or core
system libraries have been upgraded, it's recommended to reboot the system to ensure that all
changes take effect properly.

Summary

The apt-get upgrade command is a straightforward way to keep your installed packages up to
date with the latest versions available in your system's repositories. It's a key part of regular
system maintenance to ensure security and stability. For more complex upgrades that involve
changing dependencies, consider using apt-get dist-upgrade.

34. The apt-get remove command in Linux is used to uninstall or remove installed packages
from your system. Unlike apt-get purge, which also removes configuration files, apt-get
remove only removes the package binaries and leaves the configuration files intact.

●​ sudo apt-get remove package-name​ Basic Usage

What Happens When You Run apt-get remove?

1. Uninstallation of Specified Packages: The command removes the specified package(s) from
the system, but it leaves behind the configuration files in case you want to reinstall the
package later and retain your previous settings.
2. Dependency Handling: If the package being removed is a dependency for another installed
package, the system will alert you, but it won't automatically remove the dependent packages
unless you use the --auto-remove option.

3. Leaves Configuration Files: Configuration files, such as those located in /etc, are not
removed. This allows you to keep your custom settings if you reinstall the package later.

Important Considerations

- Use apt-get purge for Complete Removal:If you want to remove a package along with its
configuration files, use `sudo apt-get purge package-name` instead of sudo apt-get remove
package-name.

- Beware of Removing Critical Packages: Be cautious when removing packages, especially


those that are critical to system functionality. Removing core components like the desktop
environment or essential utilities could render your system unusable.

- Reclaiming Disk Space: After removing packages, you might want to run sudo apt-get
autoremove to clean up any orphaned dependencies that are no longer needed. Additionally,
sudo apt-get clean can be used to remove cached package files to free up disk space.

Summary

The apt-get remove command is a useful tool for uninstalling packages from your
Debian-based Linux system while keeping their configuration files intact. This command is
handy if you want to free up space or remove unnecessary software without losing your
custom settings. To fully remove a package, including its configuration files, consider using
apt-get purge.

Miscellaneous

35. The echo command in Linux is used to display a line of text or string on the terminal. It's a
simple yet powerful command that's commonly used in shell scripting and command-line
operations to output text or the results of commands.

●​ echo [options] [string] ​ Basic Usage


●​ echo "Hello, World!" ​ Display a Simple Message

Summary
The echo command is a versatile tool in Linux, useful for displaying messages, variable
values, command outputs, and more. It's an essential part of shell scripting and a fundamental
command for everyday use in the terminal.

[Link] history command in Linux displays the command history for the current user session.
It shows a list of commands that have been entered in the terminal, along with their
corresponding line numbers, allowing you to review or re-execute past commands.

●​ history​ ​ Basic Usage


●​ history 10​ Limit the Number of Displayed Commands this command will display the
last 10 commands you executed.

Important Notes

- Persistent History: The history is typically stored in a file like ~/.bash_history, which is
updated when you log out. Commands from previous sessions are loaded into memory when
you start a new terminal session.

-Customizing History: You can customize how history behaves using environment variables
such as HISTFILE (to set the history file location), HISTSIZE (to set the number of commands
stored), and HISTCONTROL (to control which commands are saved).

- Avoid Logging Certain Commands: You can prevent certain commands from being saved in
history by starting the command with a space if HISTCONTROL is set to ignorespace.

Summary

The history command is an essential tool for tracking and managing your command-line
activities. It helps you efficiently recall and re-execute previous commands, search through
your history, and manage your command history for better productivity in the terminal.

[Link] clear the command history in Linux, you can use several methods depending on how
thoroughly you want to clear the history. Here are the steps to clear the command history from
both the current session and the persistent history file.

●​ history -c Clear the Current Session's History to clear the history for the current
session (but not the saved history in the .bash_history file)
●​ cat /dev/null > ~/.bash_history Clear the History File (`.bash_history`) To clear the
history file that stores the command history between sessions
●​ history -c && > ~/.bash_history && history -w To ensure that both the session
history and history file are cleared, you can combine the commands like this:

Important Notes

- Immediate Clearing: After running these commands, the cleared history will no longer be
available in the current session or when you start a new session.
- Shell Differences:The above commands are for bash shell. If you're using another shell (like
zsh or fish), the history commands and files might differ.
- Security: If you're clearing history for privacy reasons, make sure to clear both the session
and the history file.

Summary

By using the history -c command in combination with clearing or overwriting the


.bash_history file, you can effectively clear both your session's command history and the
persistent history saved on disk. This ensures that no past commands are left accessible.

Troubleshooting in Linux often involves a variety of commands that help diagnose


and resolve issues related to system performance, network connectivity, disk
usage, and more. Below is a list of commonly used Linux troubleshooting
commands categorized by their purpose.

1. System Monitoring and Performance

- top: Displays real-time system resource usage, including CPU, memory, and processes.
- htop: An enhanced version of top with a more user-friendly interface (requires installation).
- vmstat: Provides detailed information about system processes, memory, paging, block IO,
and CPU activity.
- iostat: Reports CPU statistics and input/output statistics for devices and partitions.
- free: Displays the amount of free and used memory in the system.
- uptime: Shows how long the system has been running, along with the system load averages.

2. Process Management

- ps: Displays information about running processes.


- kill: Sends a signal to a process to terminate it
- pkill: Kills processes by name.
- lsof: Lists open files and the processes that opened them.

3. Disk and Filesystem Troubleshooting

- df: Reports file system disk space usage.


- du: Shows disk usage of files and directories.
- fsck: Checks and repairs file system errors (must be run on an unmounted file system).
- mount: Displays currently mounted file systems.
- umount: Unmounts a file system.

4. Network Troubleshooting

- ping: Tests connectivity to another networked device.


- ifconfig or ip: Displays or configures network interfaces.
- netstat: Displays network connections, routing tables, interface statistics, masquerade
connections, and multicast memberships.
- ss: Similar to `netstat`, used to display socket statistics.
- traceroute: Traces the route packets take to a network host.
- nslookup: Queries DNS to obtain domain name or IP address mapping.
- dig: A powerful DNS query tool.

5. Log File Analysis

- tail: Displays the last few lines of a file (commonly used with log files).
- grep: Searches for patterns in files (useful for log analysis)
- journalctl: Views logs managed by `systemd`.
- dmesg: Prints kernel ring buffer messages, useful for diagnosing hardware issues.

6. Package Management Troubleshooting

- apt-get (Debian/Ubuntu-based systems): Manages packages and updates.


- yum (RHEL/CentOS-based systems): Manages packages.
- dpkg: Used for low-level package management on Debian-based systems.

7. User and Permission Troubleshooting

- whoami: Displays the current user.


- id: Displays user identity, including UID, GID, and group memberships.
- chmod: Changes file permissions.
- chown: Changes file ownership.
- passwd: Changes a user's password.

8. System Information and Hardware Troubleshooting


- uname -a: Displays system information, including kernel version and architecture
- lsusb: Lists USB devices connected to the system.
- lspci: Lists PCI devices.
- dmidecode: Displays detailed hardware information.
- uptime: Shows how long the system has been running.
- top or htop: Monitors running processes and system load in real-time.

9. Service and Daemon Troubleshooting

- systemctl: Controls systemd services (start, stop, restart, check status)


- service: Manages services in non-systemd systems.

10. Common Diagnostic Commands

- strace: Traces system calls and signals, useful for debugging programs.
- lsof: Lists open files by processes, useful for finding which process is using a file or socket.
- tcpdump: Captures and analyzes network packets.

Summary

These commands form the core toolkit for troubleshooting a wide range of issues on Linux
systems. Familiarity with these tools allows you to diagnose and resolve problems efficiently,
ensuring the stability and performance of your system.

Referencies: [Link]

You might also like