0% found this document useful (0 votes)
9 views

Linux

The Linux Operating System, developed by Linus Torvalds in 1991, is a free and open-source OS built on the Linux Kernel, which manages hardware interactions. It utilizes system libraries and utilities to create various distributions, allowing users to customize their experience across different devices. Linux is widely used for servers, development, and personal computing due to its flexibility, security, and strong community support.

Uploaded by

daniyalnick038
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Linux

The Linux Operating System, developed by Linus Torvalds in 1991, is a free and open-source OS built on the Linux Kernel, which manages hardware interactions. It utilizes system libraries and utilities to create various distributions, allowing users to customize their experience across different devices. Linux is widely used for servers, development, and personal computing due to its flexibility, security, and strong community support.

Uploaded by

daniyalnick038
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

What is Linux Operating System : The Linux Operating System is a type of System Library: Linux uses system libraries,

stem libraries, also known as shared libraries, to


operating system that is similar to Unix, and it is built upon the Linux Kernel. The implement various functionalities of the operating system. These libraries contain
Linux Kernel is like the brain of the operating system because it manages how the pre-written code that applications can use to perform specific tasks. By using
computer interacts with its hardware and resources. It makes sure everything these libraries, developers can save time and effort, as they don’t need to write
works smoothly and efficiently. But the Linux Kernel alone is not enough to make the same code repeatedly. System libraries act as an interface between
a complete operating system.To create a full and functional system, the Linux applications and the kernel, providing a standardized and efficient way for
Kernel is combined with a collection of software packages and utilities, which are applications to interact with the underlying system.
together called Linux distributions.
Shell: The shell is the user interface of the Linux Operating System. It allows users
Linux History : Linus Torvalds designed the free and open-source Linux operating to interact with the system by entering commands, which the shell interprets and
system kernel in 1991. Torvalds set out to develop a free and flexible system for executes. The shell serves as a bridge between the user and the kernel,
personal computers, drawing ideas from the UNIX operating system and the forwarding the user’s requests to the kernel for processing. It provides a
MINIX operating system. Teamwork in development was encouraged with the convenient way for users to perform various tasks, such as running programs,
initial release of the Linux kernel, which attracted developers and enthusiasts managing files, and configuring the system.
globally quickly. Various open-source software packages integrated with the
Linux kernel created fully operational operating systems, occasionally referred to Hardware Layer: The hardware layer encompasses all the physical components
as Linux distributions. of the computer, such as RAM (Random Access Memory), HDD (Hard Disk Drive),
CPU (Central Processing Unit), and input/output devices. This layer is responsible
What is Linux : Linux is a free and open-source family of operating systems that is for interacting with the Linux Operating System and providing the necessary
resilient and flexible. In 1991, an individual by the name as Linus Torvalds resources for the system and applications to function properly. The Linux kernel
constructed it. The system’s source code is accessible to everyone for anyone to and system libraries enable communication and control over these hardware
look at and change, making it cool that anyone can see how the system works. components, ensuring that they work harmoniously together.
People from all across the world are urged to work together and keep developing
Linux due to its openness. System Utility: System utilities are essential tools and programs provided by the
Linux Operating System to manage and configure various aspects of the system.
What is a “distribution” : Linux distribution is an operating system that is made These utilities perform tasks such as installing software, configuring network
up of a collection of software based on Linux kernel or you can say distribution settings, monitoring system performance, managing users and permissions, and
contains the Linux kernel and supporting libraries and software. And you can get much more. System utilities simplify system administration tasks, making it easier
Linux-based operating system by downloading one of the Linux distributions and for users to maintain their Linux systems efficiently.
these distributions are available for different types of devices like embedded
devices, personal computers, etc. Around 600 + Linux Distributions are available How is the Linux Operating System Used : The Linux operating system is widely
and some of the popular Linux distributions are: MX Linux,Manjaro,Linux used across various domains due to its flexibility, security, and open-source
Mint,elementary,Ubuntu,Debian,Solus,Fedora,openSUSE,Deepin nature:

Why use Linux : Because it is free, open-source, and extremely flexible, Linux is Servers and Hosting: Powers web servers, cloud infrastructure, and database
widely utilized. For servers and developers, it is the ideal option because it offers management systems.
strong security, stability, and performance. Generally interoperable hardware, a
broad software library, and a vibrant community that offers support and regular Development: Used by developers for coding, debugging, and running
updates are the many benefits of Linux. Due to its adaptability, users can applications.
customize the operating system according to their own needs, whether they
become for personal or large enterprise use. Desktop and Personal Use: Provides secure and customizable desktop
environments.
Architecture of Linux : Linux architecture has the following components:
Cybersecurity: Essential for ethical hacking, penetration testing, and security
research.

Embedded Systems: Runs lightweight devices like routers, IoT gadgets, and smart
appliances.

Supercomputers: Dominates high-performance computing for scientific research


and simulations.

Education: A cost-effective tool for teaching programming and system


administration.

Advantages of Linux : Linux is freely available to use on the internet.It has large
community support.It provides high stability. It rarely slows down or freezes and
there is no need to reboot it after a short time.It maintains the privacy of the
user.The performance of the Linux system is much higher than other operating
systems. It allows a large number of people to work at the same time and it
handles them efficiently.It is network friendly.

Kernel: Kernel is the core of the Linux based operating system. It virtualizes the
Disadvantages of Linux : It is not very user-friendly. So, it may be confusing for
common hardware resources of the computer to provide each process with its
beginners.It has small peripheral hardware drivers as compared to windows.
virtual resources. This makes the process seem as if it is the sole process running
on the machine. The kernel is also responsible for preventing and mitigating
conflicts between different processes. Different types of the kernel are: Linux Features :-
Monolithic Kernel,Hybrid kernels,Exo kernels,Micro kernels.
Multiuser capability: Multiple users can access the same system resources like
memory, hard disk, etc. But they have to use different terminals to operate.
Multitasking: More than one function can be performed simultaneously by It was written by David Korn at AT&T Bell Labs. It is a superset of the Bourne
dividing the CPU time intelligently. shell. So it supports everything in the Bourne shell.It has interactive features. It
includes features like built-in arithmetic and C-like arrays, functions, and string-
Portability: Portability doesn't mean it is smaller in file size or can be carried in manipulation facilities. It is faster than C shell. It is compatible with script written
pen drives or memory cards. It means that it support different types of hardware. for C shell. For the Korn shell the:

Security: It provides security in three ways namely authenticating (by assigning Command full-path name is /bin/ksh,
password and login ID), authorization (by assigning permission to read, write and
execute) and encryption (converts file into an unreadable format). Non-root user default prompt is $,

Live CD/USB: Almost all Linux distros provide live CD/USB so that users can Root user default prompt is #.
run/try it without installing it.
GNU Bourne-Again Shell – Denoted as bash
Graphical User Interface (X Window system): Linux is command line based OS
but it can be converted to GUI based by installing packages. It is compatible to the Bourne shell. It includes features from Korn and Bourne
shell. For the GNU Bourne-Again shell the:
Support's customized keyboard: As it is used worldwide, hence supports
different languages keyboards. Command full-path name is /bin/bash,

Application support: It has its own software repository from where users can Default prompt for a non-root user is bash-g.gg$
download and install many applications.
(g.ggindicates the shell version number like bash-3.50$),
File System: Provides hierarchical file system in which files and directories are
arranged. Root user default prompt is bash-g.gg#.

Open Source: Linux code is freely available to all and is a community based T Shell – Denoted as tsh
development project.
It was originally developed for the Plan 9 operating system, but has since been
Different Shells in Linux :" ported to other systems, including Linux, FreeBSD, and macOS.

SHELL is a program which provides the interface between the user and an Command full-path name is /bin/tcsh,
operating system. When the user logs in OS starts a shell for user.
Default prompt for a non-root user is abhishekaslk(user):~>
Kernel controls all essential computer operations, and provides the restriction to
hardware access, coordinates all executing utilities, and manages Resources Root user default prompt is root@abhishekaslk(user):~#.
between process. Using kernel only user can access utilities provided by
operating system.
Z Shell – Denoted by zsh

Types of Shells in Linux:


Z Shell (zsh) was created by Paul Falstad in 1990 while he was a student at
Princeton University. Z Shell is an extended version of the Bourne-Again Shell
The C Shell –Denoted as csh (bash), with additional features and capabilities.

Bill Joy created it at the University of California at Berkeley. It incorporated Command full-path name is /bin/zsh,
features such as aliases and command history. It includes helpful programming
features like built-in arithmetic and C-like expression syntax. In C shell:
Default prompt for a non-root user is abhishekaslk(user)%

Command full-path name is /bin/csh,


Root user default prompt is root@abhishekaslk(user):~#

Non-root user default prompt is hostname %,


Functions Of Kernal : The kernel in Linux is the core component of the operating
system, responsible for managing hardware and system resources. Its main
Root user default prompt is hostname #. functions include:

The Bourne Shell – Denoted as sh 1. Process Management : Creates, schedules, and terminates processes.Handles
process communication and synchronization.Allocates CPU time to processes
It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is using scheduling algorithms.
faster and more preferred. It lacks features for interactive use like the ability to
recall previous commands. It also lacks built-in arithmetic and logical expression 2. Memory Management : Allocates and deallocates memory for
handling. It is default shell for Solaris OS. For the Bourne shell the: processes.Manages virtual memory using paging and swapping.Ensures efficient
memory utilization and prevents memory leaks.
Command full-path name is /bin/sh and /sbin/sh,
3. File System Management : Controls access to files and directories.Manages file
Non-root user default prompt is $, permissions and ownership.Supports multiple file systems (ext4, NTFS, FAT, etc.).

Root user default prompt is #. 4. Device Management : Interfaces with hardware devices (keyboards, printers,
disks, etc.).Uses device drivers to enable communication between hardware and
The Korn Shell - It is denoted as ksh software.Provides a standardized API for device access.
5. Inter-Process Communication (IPC) : Facilitates communication between 4. Window Managers : Unlike Windows/MacOS, X does not define how windows
processes using pipes, shared memory, message queues, etc.Ensures data should look. Instead, window managers (like GNOME, KDE, XFCE) handle the
integrity and synchronization among processes. appearance and functionality.

6. Networking : Manages network communication using protocols like 5. Protocol and Display Numbering : X uses the DISPLAY environment variable
TCP/IP.Handles data transmission, routing, and security. (:0, :1, etc.) to manage multiple screens.

7. Security & Access Control : Implements user authentication and Common X Window Components :
authorization.Uses permissions and encryption to protect data.Enforces security
policies to prevent unauthorized access. X Server: Core component that controls input/output devices. Examples: Xorg,
XFree86.
8. System Calls & User Interface : Provides system calls (e.g., fork(), exec(),
read(), write()) for applications to interact with the OS.Acts as an interface X Clients: Applications that request display services (e.g., Firefox, LibreOffice).
between user applications and hardware resources.The Linux kernel ensures
smooth interaction between software and hardware, making the operating Window Manager: Controls window placement, appearance, and interactions
system efficient, secure, and scalable. (e.g., GNOME Shell, KDE Plasma).

Linux: Linux could be a free and open supply OS supported operating system X Protocol: Defines communication between X clients and the X server.
standards. It provides programming interface still as programme compatible with
operating system primarily based systems and provides giant selection How X Windows Works in Linux : 1. The X server starts and initializes the display.
applications. A UNIX operating system additionally contains several severally
developed parts, leading to UNIX operating system that is totally compatible and
2. Users launch X clients (applications).
free from proprietary code.

3. The window manager organizes the windows.


Windows: Windows may be a commissioned OS within which ASCII text file is
inaccessible. it’s designed for the people with the angle of getting no
4. Users interact with the applications using a keyboard/mouse.
programming information and for business and alternative industrial users. it’s
terribly straightforward and simple to use. The distinction between Linux and
Alternatives to X Windows :
Windows package is that Linux is completely freed from price whereas windows
is marketable package and is expensive.
Wayland: A modern display server protocol designed to replace X for better
performance and security.

Direct Rendering: Some apps bypass X for better graphics performance (e.g.,
gaming applications).

Working Environment of Linux : The Linux working environment is a combination


of the user interface, system components, and tools that allow users to interact
with the system efficiently. It consists of :

KDE (K Desktop Environment) : KDE Plasma is a popular open-source desktop


environment for Linux and Unix-based systems. It is known for its modern look,
high customizability, and powerful features. KDE is developed by the KDE
Community and is the default desktop environment in distributions like Kubuntu,
openSUSE, Fedora KDE, and Manjaro KDE.

Key Features of KDE Plasma :

1. Modern & User-Friendly Interface : Windows-like layout: Has a taskbar, start


menu (Kickoff), system tray, and widgets.Graphical Effects: Supports
transparency, animations, and smooth transitions.

2. Highly Customizable : Change themes, icons, fonts, and colors easily.Modify


X the panel, widgets, and desktop layout to suit your workflow.Use KWin (KDE’s
Windows System (X11) in Linux : The X Window System (X11) is a framework window manager) for tiling, effects, and multi-monitor support.
that provides a graphical user interface (GUI) in Linux and Unix-based operating
systems. It acts as an interface between the hardware (display, keyboard, mouse) 3. Lightweight & Fast Performance : Uses Qt framework, optimized for
and the graphical applications. speed.Can be tuned for low-resource systems or high-performance machines.

Key Features of X Windows System : 4. KDE Applications : KDE Plasma comes with a suite of applications,
including:Dolphin – File Manager (feature-rich with tabs, split view, and
1. Client-Server Architecture : The X server manages input/output devices previews).Konsole – Terminal Emulator.Kate & KWrite – Text Editors.Kdenlive –
(display, keyboard, mouse).X clients (applications like browsers, editors) Video Editor.Okular – Document and PDF Viewer.
communicate with the X server.
5. KDE Connect (Device Integration) : Connect your Android phone to your PC for
2. Network Transparency : X allows running applications on a remote machine file sharing, SMS notifications, clipboard syncing, and remote control.
while displaying them on a local machine.
6. Multiple Workspaces & Activities : Supports virtual desktops for better
3. Modular and Extensible : The system can be customized with different multitasking.Activities help organize different workflows separately.
window managers and desktop environments.
7. Wayland & X11 Support : Supports X11 (legacy display server) and Wayland
(modern, secure alternative).

GNOME (GNU Network Object Model Environment) : GNOME is a popular,


open-source desktop environment for Linux and Unix-based operating systems. It
is known for its clean, minimalistic design, ease of use, and modern workflow.
GNOME is the default desktop environment in Ubuntu, Fedora, Debian, and Red
Hat Enterprise Linux (RHEL).

Key Features of GNOME :-

1. Minimalistic & Modern UI : Uses a single-panel layout with a top bar, Activities
Overview, and a dock.No desktop icons by default (but can be enabled with
extensions).

2. Activities Overview for Multitasking : Press Super (Windows key) to enter


Activities Overview, where you can : Search for applications.Manage virtual
workspaces (dynamic workspaces). View all open applications.
The Linux File System Hierarchy follows the Filesystem Hierarchy Standard
(FHS), which defines the structure and contents of directories in a Linux operating
3. GNOME Shell (Dynamic Desktop Experience) : A streamlined interface with
system. It organizes files systematically to ensure consistency across
smooth animations.Uses Wayland by default for security and better
distributions. Below are the main components of the Linux file system hierarchy:
performance.Extensions can modify the interface.

1. Root Directory (/) : The top-most directory in Linux.All other directories and
4. Extensions & Customization : GNOME is less customizable than KDE but allows
files are placed under /.It contains essential system directories like /bin, /etc,
tweaks using : GNOME Tweaks – Adjust themes, fonts, and icons.GNOME
/var, etc.
Extensions – Add extra functionality like a system tray or desktop icons.dconf
Editor – Advanced configuration tool.
2. Essential System Directories :

5. Core GNOME Applications : GNOME comes with a suite of default


/bin (Binary) : Contains essential command-line binaries (executables) used by all
applications : Files (Nautilus) – File Manager,GNOME Terminal – Terminal
users.Examples: ls, cp, mv, rm, cat, echo.
Emulator,Gedit – Text Editor,Evince – Document Viewer,Totem – Video Player

/sbin (System Binaries) : Contains system administration commands and utilities.


6. Wayland & X11 Support : GNOME defaults to Wayland for better security and
Examples: fdisk, fsck, shutdown, reboot.
performance. Supports X11 for legacy applications.

/etc (Configuration Files) : Stores system-wide configuration files.


7. Performance & Efficiency : Designed for a clutter-free experience with smooth
transitions. Can feel heavy on lower-end hardware but works well with
Examples: /etc/passwd (user information), /etc/fstab (filesystem mount settings).
optimizations.

/lib (Libraries) : Holds essential shared libraries needed by binaries in /bin and
XFCE4 (XForms Common Environment 4) : XFCE4 is a lightweight, fast, and highly
/sbin.
efficient desktop environment for Linux and Unix-like operating systems. It is
designed to be resource-friendly while still providing a traditional and user-
friendly interface. XFCE is a great choice for older hardware or users who prefer Examples: libc.so, ld-linux.so.
speed over visual effects.
/lib64 (64-bit Libraries) : Contains 64-bit versions of shared libraries for 64-bit
Key Features of XFCE4 : systems.

1. Lightweight & Fast Performance : Uses low system resources, making it ideal 3. User and Application Directories : /home (User Home Directories)
for older or low-power computers.Faster than GNOME and KDE due to minimal
background services. Contains personal directories for each user.

2. Traditional Desktop Layout : Windows-like interface with a panel, menu, Example: /home/user1, /home/user2.
system tray, and icons.Supports multiple panels and customizable widgets.
/root (Root User’s Home Directory) : Home directory for the root
3. Highly Customizable : Change themes, icons, and fonts using the XFCE Settings (superuser).Separate from /home to maintain security.
Manager. Supports third-party themes and extensions.Customizable panel layout
and menu structure. /usr (User Binaries & Applications) : Stores user-related programs, libraries, and
documentation.
4. Core XFCE Applications : XFCE includes a set of lightweight applications, such
as : Thunar – File Manager (fast and minimal).XFCE Terminal – Terminal Subdirectories : /usr/bin: Non-essential user binaries (e.g., vim, gcc).
Emulator.Mousepad – Text Editor. Ristretto – Image Viewer.Parole – Media
Player. /usr/sbin: Non-essential system binaries (e.g., apache2, sshd).

5. Window & Workspace Management : Supports virtual desktops for better /usr/lib: Libraries for /usr/bin and /usr/sbin.
multitasking.Uses xfwm4 (XFCE’s window manager) for snappy performance.
/usr/local: Locally installed programs (outside package manager control).
6. Low Resource Usage : Uses very little RAM and CPU, making it perfect for
systems with limited hardware.Consumes less power, making it ideal for laptops. 4. System Runtime and Temporary Data :
/var (Variable Data) The Linux file system is a structured way to store and manage data on storage
devices like hard disks, SSDs, and USB drives. It consists of several key parts that
Stores logs, caches, spool files, and other dynamic data. work together to ensure data is efficiently stored, accessed, and managed. Below
is a detailed breakdown of the different parts of a Linux file system.
Subdirectories : /var/log: Log files (e.g., /var/log/syslog).
1. Boot Block (MBR/GPT) : The boot block is the first sector of a storage device.It
/var/tmp: Temporary files that persist after a reboot. contains the Master Boot Record (MBR) or GUID Partition Table (GPT), which
stores information about partitions and the bootloader.MBR: Used in older
/tmp (Temporary Files) systems, supports up to 2TB disks.GPT: Used in modern systems, supports larger
disks and more partitions.
Stores temporary files created by applications.Files here are usually deleted on
system reboot. 2. Superblock : The superblock contains critical metadata about the file system.It
stores information such as:File system type (e.g., ext4, XFS, Btrfs).Total number of
inodes and blocks. Free and used block counts.Block size.Mount status and state
5. Device and Special Purpose Directories :
of the file system.The superblock is replicated multiple times across the disk to
prevent data loss.
/dev (Device Files) : Contains files representing hardware devices.

3. Inode Table (Index Nodes) : Inodes store metadata about files and
Examples : /dev/sda1: First partition of the first hard drive.
directories.Each file/directory has an inode number, which contains:File type
(regular file, directory, symbolic link, etc.).File permissions and ownership (user,
/dev/null: Discard any data written to it.
group).File size.Time stamps (created, modified, accessed).Pointers to data blocks
storing the actual file content.The inode does not store the file name—file names
/proc (Process Information) are stored in directory entries.

A virtual filesystem providing information about system processes. 4. Data Blocks : The actual content of files is stored in data blocks.The inode table
keeps track of which blocks belong to which files.If a file is large, it spans multiple
Example : /proc/cpuinfo: CPU details. blocks, and the inode holds pointers to these blocks.

/proc/meminfo: Memory usage. 5. Journal (for Journaling File Systems) : A journal is used in journaling file
systems (ext3, ext4, XFS, Btrfs) to prevent data corruption.Before writing changes
/sys (System Information) to the main file system, they are logged in the journal.If the system crashes
during a write operation, the journal can help recover lost data.
Exposes kernel and hardware-related system information.
6. Directory Structure : Directories in Linux are special files that store references
Works closely with /proc. (links) to files and other directories.A directory entry contains:File
name.Corresponding inode number.The ls -i command can display the inode
/mnt (Mount Directory) number of files.

Temporary mount point for manually mounted filesystems. 7. Special File Types : Apart from regular files and directories, Linux supports :
Symbolic Links (Soft Links): Point to another file or directory.
/media (Removable Media)
Hard Links: Create another name for an existing file, sharing the same inode.
Automatically mounted removable devices like USB drives and CDs.
Device Files (/dev): Represent hardware devices as files.
6. Boot and Kernel Files :
Pipes & Sockets: Used for inter-process communication.
/boot (Boot Files)
Here are the commands to add a user, add a group, and delete a group in Linux
Contains files required for booting the system. for the given user and group names:

Examples : vmlinuz: Compressed Linux kernel. 1. Add a New User (testuse) : sudo useradd testuse

initrd: Initial RAM disk image. This creates a new user testuse without a home directory.

/opt (Optional Software) To create a home directory, use:

Stores third-party software and add-on packages. sudo useradd -m testuse

7. Special Purpose Directories : /run (Runtime Data) 2. Add a New Group (testgroup) : sudo groupadd testgroup

Holds system runtime data like process IDs (/run/sshd.pid). This creates a new group named testgroup.

Replaces /var/run in newer Linux versions. 3. Add User testuse to Group testgroup : sudo usermod -aG testgroup testuse

/srv (Service Data) This adds testuse to the testgroup without removing them from other groups.

Stores data for system services like web and FTP servers. 4. Verify Group Membership : groups testuse

This will list all groups the user testuse belongs to.
5. Delete the Group (testgroup) : sudo groupdel testgroup Applies ownership change to all files inside the directory.

This removes the group testgroup (make sure no active processes are using it). chgrp (Change Group Ownership) : Used to change the group associated with a
file.
File Permissions in Linux : Linux uses a permission system to control access to
files and directories. Each file and directory has three types of permissions 1. Change Group Ownership : chgrp newgroup file.txt
assigned to three categories of users.
Assigns newgroup as the group for file.txt.
1. Types of Users : Owner (u): The user who created the file.Group (g): A group
of users who can access the file. Others (o): All other users. 2. Change Group Ownership Recursively : chgrp -R newgroup /path/to/directory

chmod (Change File Permissions) : Used to change file permissions using Changes group ownership for all files inside the directory.
symbolic (rwx) or numeric (0-7) notation.
File and Directory Management Commands in Linux : Linux provides various
1. Using Numeric Mode : Each permission is represented by a number: commands to manage files and directories. Here are some commonly used
commands with short examples:
7 → Read (4) + Write (2) + Execute (1) = rwx
1. mkdir (Make Directory) : Used to create new directories.
6 → Read (4) + Write (2) = rw-
Example: Create a Directory
5 → Read (4) + Execute (1) = r-x
mkdir myfolder
4 → Read only = r--
Creates a directory named myfolder.
0 → No permission = ---
Example: Create Multiple Directories
Example: Grant full permission to the owner, read & execute for group, and read-
only for others mkdir folder1 folder2 folder3

chmod 754 file.txt Creates folder1, folder2, and folder3.

Owner (7 → rwx). Example: Create Parent Directories

Group (5 → r-x). mkdir -p parent/child/grandchild

Others (4 → r--). Creates a nested directory structure.

2. Using Symbolic Mode : + → Add permission. 2. rmdir (Remove Directory) : Used to delete empty directories.

- → Remove permission. Example: Remove an Empty Directory : rmdir myfolder

= → Set exact permissions. Deletes myfolder if it is empty.

Example: Add execute permission to the owner Example: Remove Multiple Empty Directories

chmod u+x file.txt rmdir folder1 folder2

Example: Remove write permission from group Deletes folder1 and folder2 if they are empty.

chmod g-w file.txt Note: To delete non-empty directories, use rm -r.

Example: Set permissions exactly to read & write for everyone 3. cd (Change Directory) : Used to navigate between directories.

chmod ugo=rw file.txt Example: Move into a Directory

chown (Change File Ownership) : Used to change the owner and/or group of a cd myfolder
file.
Changes into myfolder.
1. Change the Owner : chown newuser file.txt
Example: Move to Parent Directory
Assigns ownership of file.txt to newuser.
cd ..
2. Change Owner and Group : chown newuser:newgroup file.txt
Moves up one level.
Changes the owner to newuser and group to newgroup.
Example: Move to Home Directory
3. Change Ownership Recursively (for all files in a directory) : chown -R
newuser:newgroup /path/to/directory cd ~
Takes you to the home directory. 2. Show the Last 5 Lines : tail -n 5 file.txt

Example: Move to the Root Directory 3. Show the Last 20 Bytes : tail -c 20 file.txt

cd / 4. Follow a File (Live Updates) : tail -f log.txt

Takes you to the root (/) directory. Useful for monitoring real-time logs.

4. pwd (Print Working Directory) : Displays the current directory's full path. 3. cut (Extract Specific Columns or Characters) : The cut command extracts
portions of text from each line of a file.
Example: Show Current Directory
Syntax : cut [options] filename
pwd
Examples : 1. Extract the First 10 Characters : cut -c 1-10 file.txt
Output : /home/user/myfolder
2. Extract the 2nd and 4th Columns (Using Delimiter :) : cut -d':' -f2,4 file.txt
5. ls (List Files and Directories) : Used to display files and directories.
3. Extract the First Column (Default Delimiter: Tab) : cut -f1 file.txt
Example: List Files in Current Directory
4. paste (Merge Lines or Columns) : The paste command merges lines or columns
ls from multiple files.

Example: List Files with Details Syntax : paste [options] file1 file2

ls -l Examples : 1. Merge Two Files Line by Line : paste file1.txt file2.txt

Displays detailed information like permissions, owner, size, and modification Each line from file1.txt and file2.txt is joined with a Tab.
date.
2. Merge Using a Comma Instead of a Tab : paste -d ',' file1.txt file2.txt
Example: Show Hidden Files
3. Merge Each Line Into a Single Line : paste -s file.txt
ls -a
Converts a multi-line file into a single-line output.
Lists all files, including hidden files (starting with .).
5. sort (Sort Lines in a File) : The sort command arranges lines in alphabetical or
Example: List Files with Human-Readable Sizes numerical order.

ls -lh Syntax : sort [options] filename

Displays sizes in KB, MB, or GB. Examples : 1. Sort Alphabetically : sort names.txt

Example: Sort Files by Modification Time 2. Sort in Reverse Order : sort -r names.txt

ls -lt 3. Sort Numerically : sort -n numbers.txt

Sorts files by latest modification time. 4. Sort by Second Column (Using : as Delimiter) : sort -t':' -k2 file.txt

Filter Commands in Linux : Filter commands in Linux process text data by -t':' → Specifies : as the delimiter
modifying or extracting specific parts of a file. These commands are mostly used
with pipes (|) to filter large data efficiently. -k2 → Sorts based on the 2nd column

1. head (Display First N Lines of a File) : The head command is used to display the 6. uniq (Remove Duplicate Lines) : The uniq command removes consecutive
first 10 lines of a file by default. duplicate lines.

Syntax : head [options] filename Syntax : uniq [options] filename

Examples : 1. Show the First 10 Lines (Default) : head file.txt Examples : 1. Remove Duplicate Lines : uniq file.txt

2. Show the First 5 Lines : head -n 5 file.txt Only removes consecutive duplicates.

3. Show First 20 Bytes : head -c 20 file.txt 2. Count Duplicate Lines : uniq -c file.txt

2. tail (Display Last N Lines of a File) : The tail command shows the last 10 lines Prefixes each line with count of occurrences.
of a file by default.
3. Show Only Duplicate Lines : uniq -d file.txt
Syntax : tail [options] filename
4. Show Only Unique Lines : uniq -u file.txt
Examples : 1. Show the Last 10 Lines (Default) : tail file.txt
7. grep (Search for a Pattern in a File) : The grep command searches for specific
words, phrases, or patterns.

Syntax : grep [options] "pattern" filename

Examples : 1. Search for the Word "Linux" : grep "Linux" file.txt

2. Case-Insensitive Search : grep -i "linux" file.txt

3. Show Line Numbers for Matches : grep -n "error" logfile.txt

4. Search for an Exact Word : grep -w "root" passwd.txt

Matches root but not rooted.

5. Invert Search (Show Non-Matching Lines) : grep -v "Linux" file.txt

6. Recursive Search in All Files : grep -r "error" /var/log/

Searches for "error" inside all files in /var/log/.

Text Editors in Linux: vi and vim : Linux provides powerful text editors like vi and
vim for editing configuration files, writing scripts, and developing code.

vi (Visual Editor) → The default text editor in Unix/Linux.


Communication Commands in Linux : Linux provides several communication
commands to send messages, chat, or send emails between users on the same
vim (Vi IMproved) → An enhanced version of vi with additional features like
system or across a network.
syntax highlighting, undo, and plugins.

1. mesg (Enable/Disable Messages) : The mesg command controls whether other


1. Modes in vi/vim : vi and vim have three primary modes:
users can send messages to your terminal.

1. Command Mode → Default mode (navigate, copy, delete, save, etc.).


Syntax : mesg [y|n]

2. Insert Mode → For typing and editing text.


y → Allows messages.

3. Ex Mode (Last Line Mode) → For saving, quitting, and executing commands.
n → Blocks messages.

Examples : Enable message reception : mesg y

Disable message reception : mesg n

Check current status : mesg

Output : is y → Messages are allowed.


2. Opening a File in vi/vim : vi filename
is n → Messages are blocked.
vim filename
2. talk (Real-Time Chat with Another User) : The talk command allows two users
If filename exists, it opens the file. to communicate interactively in real-time.

If filename doesn’t exist, it creates a new file. Syntax : talk username@hostname

Example : To start a chat with user1 on the same system:

talk user1

If the user is on another system (192.168.1.10):

talk [email protected]

The recipient must accept the chat request using:

talk username

3. write (Send Message to a User) : The write command sends a one-way


message to another user’s terminal.
Syntax : write username [tty] pkill firefox → Kills all Firefox processes.

If the user is logged in multiple times, specify their TTY. pkill -u user1 → Kills all processes owned by user1.

Example : Send a message to user1: 5. nice (Set Process Priority) : The nice command starts a new process with a
specific priority. The priority range is from -20 (highest priority) to 19 (lowest
write user1 priority), with the default being 0.

Start typing the message and press Ctrl + D to end the message. nice -n 10 python script.py → Runs python script.py with a lower priority.

4. wall (Broadcast Message to All Users) : The wall command sends a message to sudo nice -n -5 ./heavy_task → Runs a process with a higher priority (negative
all logged-in users. values require sudo).

Syntax : wall "message"

Example : Send a broadcast message:

wall "System maintenance at 10 PM. Please log out."

Only root users can send messages when users have mesg n enabled.

5. mail (Send Emails from Terminal) : The mail command is used to send emails
from the terminal.

Syntax : mail -s "subject" [email protected]

Example : Send an email : echo "Hello, this is a test email." | mail -s "Test Email"
[email protected]

Read emails : mail

Delete an email (e.g., email number 2) : d 2

Process Management Commands in Linux : Process management commands in


Linux help monitor, control, and manage system processes efficiently. Here’s a
detailed explanation of key commands:
What is RAID : RAID (Redundant Array of Independent Disks) is a storage
1. ps (Process Status) : The ps command displays information about active technology that combines multiple physical disks into a single logical unit to
processes running on the system. By default, it shows only processes associated improve performance, redundancy, or both.Linux supports different RAID levels,
with the current terminal session. Some common usages include: each offering various advantages in terms of speed, fault tolerance, and storage
efficiency.
ps → Lists processes in the current shell session.
Types of RAID in Linux : RAID can be implemented in two ways:
ps -e → Shows all system processes.
1. Hardware RAID – Managed by a dedicated RAID controller.
ps aux → Displays all processes with detailed information like CPU usage,
memory usage, and process IDs (PIDs). 2. Software RAID – Managed by the Linux kernel using tools like mdadm.

ps -u username → Lists processes owned by a specific user. RAID Levels and Their Features :

2. top (Real-Time Process Monitoring) : The top command provides a real-time 1. RAID 0 (Striping, No Redundancy) : Data is split across multiple disks to
view of system processes, displaying information like CPU and memory improve speed.No redundancy – If one disk fails, all data is lost.Minimum Disks
usage.Running top opens an interactive interface where processes are updated Required: 2
dynamically.Press k to kill a process, r to renice (change priority), Shift + P to sort
by CPU usage, and Shift + M to sort by memory usage.Press q to exit top.
Use Case: High-speed applications like video editing.

3. kill (Terminate Processes by PID) : The kill command is used to terminate


Example Setup (Linux Software RAID) : mdadm --create --verbose /dev/md0 --
processes using their Process ID (PID).
level=0 --raid-devices=2 /dev/sdb /dev/sdc

kill PID → Sends the default SIGTERM signal to terminate a process gracefully.
2. RAID 1 (Mirroring, High Redundancy) : Data is duplicated (mirrored) on two
disks.Provides fault tolerance – If one disk fails, data remains safe on the
kill -9 PID → Forcefully kills a process using SIGKILL. other.Minimum Disks Required: 2

kill -1 PID → Restarts a process using SIGHUP. Use Case: Critical systems where data loss is unacceptable.

4. pkill (Kill Process by Name) : Instead of using PIDs, the pkill command allows Example Setup : mdadm --create --verbose /dev/md0 --level=1 --raid-
killing processes by their name. devices=2 /dev/sdb /dev/sdc
3. RAID 5 (Striping with Parity, Balanced Performance & Redundancy) : Data is pvdisplay
striped across disks with parity information stored on different disks.Provides
fault tolerance – Can survive one disk failure.Minimum Disks Required: 3 Step 2: Create a Volume Group (VG)

Use Case: Balanced performance and redundancy for databases & servers. Create a volume group named vg_data:

Example Setup : mdadm --create --verbose /dev/md0 --level=5 --raid- vgcreate vg_data /dev/sdb /dev/sdc
devices=3 /dev/sdb /dev/sdc /dev/sdd
Check VGs:
4. RAID 6 (Striping with Double Parity, Extra Fault Tolerance) : Similar to RAID 5
but stores two sets of parity data for extra security.Can survive two disk vgdisplay
failures.Minimum Disks Required: 4
Step 3: Create Logical Volumes (LV)
Use Case: Enterprise environments needing high fault tolerance.
Create a 50GB logical volume named lv_home:
Example Setup : mdadm --create --verbose /dev/md0 --level=6 --raid-
devices=4 /dev/sdb /dev/sdc /dev/sdd /dev/sde lvcreate -L 50G -n lv_home vg_data

5. RAID 10 (RAID 1 + RAID 0, Best of Both Worlds) : Combines RAID 1 (mirroring) Or create an LV using all free space:
and RAID 0 (striping).Provides speed and redundancy but requires more
disks.Minimum Disks Required: 4
lvcreate -l 100%FREE -n lv_storage vg_data

Use Case: High-performance databases and critical applications.


Check LVs:

Example Setup : mdadm --create --verbose /dev/md0 --level=10 --raid-


lvdisplay
devices=4 /dev/sdb /dev/sdc /dev/sdd /dev/sde

Step 4: Format and Mount the LV


What is LVM : LVM (Logical Volume Manager) is a flexible disk management
system in Linux that allows users to create, resize, and manage storage
Format the logical volume with the ext4 filesystem:
dynamically without unmounting partitions or losing data.

mkfs.ext4 /dev/vg_data/lv_home
Advantages of LVM :Dynamic Partitioning: Resize partitions (logical volumes)
without rebooting. Better Storage Utilization: Combine multiple physical disks
Create a mount point and mount the LV:
into a single logical volume.

mkdir /mnt/home
Snapshots: Take instant backups of volumes.

mount /dev/vg_data/lv_home /mnt/home


RAID-like Features: Striping (RAID 0), Mirroring (RAID 1).

Step 5: Resize Logical Volumes


LVM Components :

Increase LV size (e.g., add 10GB):


1. Physical Volume (PV) : A PV is a physical disk or partition used in LVM.

lvextend -L +10G /dev/vg_data/lv_home


Example: /dev/sdb, /dev/sdc1

resize2fs /dev/vg_data/lv_home # Resize filesystem


2. Volume Group (VG) : A VG is a collection of multiple PVs that act as a single
storage pool.
Reduce LV size (use caution):
Example: vg_data
umount /dev/vg_data/lv_home
3. Logical Volume (LV) : An LV is a partition created from the VG that can be
formatted and mounted like a normal disk. lvreduce -L -10G /dev/vg_data/lv_home

Example: /dev/vg_data/lv_home resize2fs /dev/vg_data/lv_home

4. Physical Extents (PE) : LVM divides disks into PEs (Physical Extents), which are mount /dev/vg_data/lv_home /mnt/home
small fixed-size chunks (default: 4MB).
Step 6: Take LVM Snapshots (Backup Purpose)
How to Use LVM in Linux :
Create a snapshot of lv_home:
Step 1: Create Physical Volumes (PV)
lvcreate -L 5G -s -n lv_home_snapshot /dev/vg_data/lv_home
Convert raw disks or partitions into LVM physical volumes:
Remove snapshot:
pvcreate /dev/sdb /dev/sdc
lvremove /dev/vg_data/lv_home_snapshot
Check PVs:
Who is a System Administrator : A System Administrator (SysAdmin) is
responsible for managing and maintaining a company’s IT infrastructure, servers,
networks, and security systems to ensure smooth and efficient operations. They 3. Kernel initializes hardware and starts system processes.
handle installation, configuration, troubleshooting, security, and performance
monitoring of hardware and software. 4. The OS boots into the user environment.

Key Responsibilities of a System Administrator : GRUB Commands : Update GRUB configuration:

1. Server and System Management : Install, configure, and maintain operating sudo update-grub
systems (Linux, Windows, etc.).Manage server hardware, storage, and virtual
machines (VMs).Perform software updates, patches, and security fixes.Monitor Reinstall GRUB bootloader (for MBR-based systems):
CPU, memory, and disk usage to prevent performance issues.
sudo grub-install /dev/sda
2. User and Access Management : Create, manage, and delete user accounts and
permissions. Set up role-based access control (RBAC) for security.Manage 2. LILO (Linux Loader) – Legacy Boot Loader : LILO is an older boot loader that
authentication systems like Active Directory (AD), LDAP, SSH keys. was widely used before GRUB. It is simpler but lacks advanced features.

3. Network Administration : Configure and maintain routers, switches, and Features of LILO : Simple and lightweight bootloader.Supports multiple OS
firewalls.Monitor network traffic and bandwidth usage.Set up and manage VPNs, booting, but requires manual reconfiguration.Does not have a menu interface like
DNS, DHCP, and IP addressing. Troubleshoot connectivity issues and optimize GRUB.Limited support for modern file systems.Cannot dynamically detect new
network performance. kernels (must be manually updated).No network boot support.

4. Security Management : Implement firewalls, intrusion detection systems (IDS), LILO Boot Process : 1. BIOS loads LILO from the MBR.
and encryption.Regularly update antivirus and malware protection.Conduct
security audits, log monitoring, and vulnerability assessments.Enforce password
2. LILO loads the Linux kernel.
policies, multi-factor authentication (MFA), and access controls.

3. The kernel initializes system processes.


5. Backup and Disaster Recovery : Schedule automatic backups using tools like
rsync, Bacula, or Veeam.Test data recovery procedures to prevent data
4. The OS starts running.
loss.Maintain redundant systems and disaster recovery plans (DRP).

LILO Commands : Install LILO bootloader:


6. Virtualization and Cloud Management : Set up and manage VMware, KVM,
Hyper-V, or VirtualBox virtual machines.Deploy and maintain cloud services
sudo lilo
(AWS, Azure, Google Cloud). Monitor cloud performance, security, and costs.

Update LILO configuration:


7. Scripting and Automation : Write shell scripts (Bash, Python, PowerShell) to
automate tasks. Use Ansible, Puppet, or Chef for configuration
management.Automate log monitoring, backups, and patch management. sudo lilo -v

8. Log Management and Monitoring : Use tools like Nagios, Zabbix, Prometheus,
or Grafana to monitor servers.Analyze system logs using journalctl, syslog, and
ELK Stack (Elasticsearch, Logstash, Kibana).Troubleshoot issues based on log
reports and alerts.

9. Troubleshooting and Technical Support : Respond to hardware and software


issues reported by users.Diagnose and fix performance bottlenecks, crashes, and
system failures.Provide helpdesk support for IT-related issues.

10. Compliance and Documentation : Ensure compliance with IT policies, GDPR,


HIPAA, PCI-DSS standards.Maintain documentation for system configurations,
processes, and security policies.Train users on best practices for security and IT
usage.

A boot loader is a program that loads the operating system (OS) into memory
when a computer starts. It is the first software that runs after the BIOS/UEFI
initializes the hardware.

1. GRUB (Grand Unified Bootloader) : GRUB is the most widely used bootloader
in modern Linux systems. It is highly flexible, powerful, and supports multiple Wo
OSes. rking of Various Servers in Linux : Each server in Linux performs a specific role in
networking, file sharing, web hosting, and remote access. Below is a detailed
Features of GRUB : Supports multiple operating systems (Linux, Windows, explanation of how each server works, along with its key components.
etc.).Supports different file systems (ext4, XFS, FAT32, NTFS, etc.).Allows boot-
time kernel parameter modifications.Provides a menu-driven interface for 1. DHCP Server (Dynamic Host Configuration Protocol) : A DHCP server
booting.Supports password protection for security.Can boot from network (PXE automatically assigns IP addresses and network configurations to clients.
booting).Supports Logical Volume Manager (LVM) and RAID.
Working : 1. Client Broadcasts a DHCP Discovery Request → The device (PC,
GRUB Boot Process : 1. BIOS/UEFI loads GRUB into memory. mobile, etc.) sends a request to find a DHCP server.

2. GRUB loads the kernel and initramfs. 2. DHCP Server Responds with an Offer → The server offers an available IP
address and network settings.
3. Client Requests the Offered IP → The client accepts the offer by sending a Working : 1. User Connects Using Telnet → telnet 192.168.1.10
DHCP Request.
2. Server Authenticates the User → The user enters a username and password.
4. DHCP Server Assigns the IP → The server confirms the assignment and updates
its database. 3. User Gains Shell Access → The client gets a remote command-line interface.

Real-Life Example : When you connect your phone to Wi-Fi, the router's DHCP 4. User Executes Commands → The user can manage files, install software, etc.
server assigns an IP address dynamically.
Real-Life Example : An admin logs into a Linux server remotely using Telnet (not
2. DNS Server (Domain Name System) : A DNS server converts human-readable secure, replaced by SSH).
domain names (e.g., google.com) into IP addresses.
6. FTP Server (File Transfer Protocol) : FTP is used to transfer files between a
Working : 1. User Enters a Domain Name → A user types www.example.com in a client and a server.
browser.
Working : 1. User Connects to FTP Server → ftp 192.168.1.10
2. DNS Resolver Contacts Root Server → The local DNS resolver checks its cache.
If the domain isn’t found, it queries the root DNS server. 2. User Authenticates with Username and Password.

3. Root Server Directs to TLD Server → The root server sends the request to the 3. User Browses Files → List directories using : ls
Top-Level Domain (TLD) server (e.g., .com).
4. File Transfer Happens → Download a file:
4. TLD Server Directs to the Authoritative DNS Server → The TLD server sends the
request to example.com’s authoritative DNS server. get file.txt

5. IP Address is Returned → The authoritative DNS server responds with the IP Upload a file:
(192.168.1.20).
put file.txt
6. Browser Connects to the Website → The browser loads the website using the
IP address.
5. User Disconnects → bye

Real-Life Example : When you visit www.youtube.com, your ISP’s DNS server
Real-Life Example : Web developers upload website files to a hosting server using
resolves it to 142.250.183.206.
FTP clients like FileZilla.

3. Squid Proxy Server : A Squid proxy server acts as an intermediary between


7. Samba Server : Samba allows file and printer sharing between Linux and
clients and the internet, caching content and filtering requests.
Windows systems.

Working : 1. User Sends a Request → A user tries to access www.example.com.


Working : 1. Samba Server Runs on Linux → It shares directories via SMB
protocol.
2. Squid Checks Cache → If a cached copy is available, Squid serves the page
immediately.
2. Windows Client Accesses the Share → \\192.168.1.10\SharedFolder

3. If Not Cached, Squid Fetches Data → Squid requests the page from the original
3. User Authenticates → The user enters login credentials.
website.

4. User Reads/Writes Files → Files are shared and modified across OS platforms.
4. Squid Caches the Response → The website content is stored for future
requests.
5. Session Closes When Done.

5. User Receives the Response → The client gets the webpage, either from the
Real-Life Example : A Linux file server shares files across Windows machines in an
cache or the web.
office.

Real-Life Example : A company uses Squid to block social media websites while
What is Shell Scripting : A shell script is a program written for the Linux shell to
allowing access to work-related sites.
automate tasks. It contains a series of commands that execute sequentially. Shell
scripts are used for system administration, task automation, and process
4. Apache Web Server : Apache is an open-source web server used for hosting
management.
websites and serving web pages.

Simple Shell Script to Display "Hello World"


Working : 1. Client Sends an HTTP Request → A user enters www.example.com in
a browser. 2. Apache Receives the Request → The request is processed based
Step 1: Create a Script File : Open a terminal and create a file:
on Virtual Hosts settings. 3. Apache Fetches the Web Page → It retrieves
index.html or index.php from /var/www/html/. 4. Apache Sends the Response
nano hello.sh
→ The server delivers the webpage to the user's browser.

Step 2: Write the Script : Add the following lines: #!/bin/bash


5. Browser Displays the Webpage → The user sees the website content.

echo "Hello, World!"


Real-Life Example : When you visit www.wikipedia.org, Apache processes your
request and delivers Wikipedia’s homepage.
#!/bin/bash → Specifies the interpreter (Bash shell).
5. Telnet Server : Telnet provides a remote text-based login to another computer
over a network. echo "Hello, World!" → Prints "Hello, World!" to the terminal.
Step 3: Save and Exit : Press CTRL + X, then Y, and hit Enter to save the file. elif [ $num -gt 5 ]; then

Step 4: Make the Script Executable : chmod +x hello.sh echo "Number is greater than 5 but less than or equal to 15"

Step 5: Run the Script : ./hello.sh else

Output : Hello, World! echo "Number is 5 or less"

Control Structures in Shell Scripting : Control structures in shell scripting allow fi


scripts to make decisions, loop through data, and execute commands
conditionally. They include: Output : Number is greater than 5 but less than or equal to 15

1. Conditional Statements (if, if-else, case) – Execute commands based on (d) case Statement : Used for multiple choices, similar to switch-case in other
conditions. languages.

2. Looping Statements (for, while, until) – Repeat commands multiple times. Example : #!/bin/bash

3. Jump Statements (break, continue, exit) – Control the flow of execution. echo "Enter a number (1-3):"

1. Conditional Statements : read num

(a) if Statement : Executes commands only if a condition is true. case $num in

Syntax : if [ condition ]; then 1) echo "You chose One";;

commands 2) echo "You chose Two";;

fi 3) echo "You chose Three";;

Example : #!/bin/bash *) echo "Invalid choice";;

num=10 esac

if [ $num -gt 5 ]; then Output (if user enters 2):

echo "Number is greater than 5" You chose Two

fi 2. Looping Statements :

Output : Number is greater than 5 (a) for Loop : Repeats commands for a fixed number of times.

(b) if-else Statement : Executes different commands for true and false conditions. Example : #!/bin/bash

Example : #!/bin/bash for i in 1 2 3 4 5

num=3 do

if [ $num -gt 5 ]; then echo "Iteration: $i"

echo "Number is greater than 5" done

else Output : Iteration: 1

echo "Number is not greater than 5" Iteration: 2

fi Iteration: 3

Output : Number is not greater than 5 Iteration: 4

(c) if-elif-else Statement : Checks multiple conditions. Iteration: 5

Example : #!/bin/bash (b) while Loop : Executes commands while a condition is true.

num=10 Example : #!/bin/bash

if [ $num -gt 15 ]; then count=1

echo "Number is greater than 15" while [ $count -le 5 ]


do Value: 3

echo "Count: $count" Value: 4

((count++)) (b) continue Statement : Skips the current iteration and moves to the next one.

done Example : #!/bin/bash

Output : Count: 1 for i in {1..5}

Count: 2 do

Count: 3 if [ $i -eq 3 ]; then

Count: 4 continue

Count: 5 fi

(c) until Loop : Executes commands until a condition becomes true. echo "Value: $i"

Example : #!/bin/bash done

num=1 Output : Value: 1

until [ $num -gt 5 ] Value: 2

do Value: 4

echo "Number: $num" Value: 5

((num++)) (c) exit Statement : Exits the script immediately.

done Example : #!/bin/bash

Output : Number: 1 echo "Before exit"

Number: 2 exit 1

Number: 3 echo "This line will not execute"

Number: 4 Output : Before exit

Number: 5 Meta Characters in Linux Shell Scripting : Meta characters are special symbols
that have a unique meaning in the Linux shell. They are used for wildcards,
3. Jump Statements : redirections, piping, quoting, and command execution.

(a) break Statement : Exits a loop when a condition is met. Common Meta Characters and Their Uses :

Example : #!/bin/bash

for i in {1..10}

do

if [ $i -eq 5 ]; then

break

fi

echo "Value: $i"

done

Output : Value: 1

Value: 2
[ condition ] && command1 || command2 → Executes command1 if the
condition is true, otherwise executes command2.

Example Output : Enter a number : 10

10 is Even

2. Check Prime Number: Script:

#!/bin/bash

echo "Enter a number:"

read num

is_prime=1

for ((i = 2; i * i <= num; i++)); do

[ $((num % i)) -eq 0 ] && is_prime=0 && break

done

[ $num -gt 1 ] && [ $is_prime -eq 1 ] && echo "$num is Prime" || echo "$num is
Not Prime"

Explanation : A prime number is only divisible by 1 and itself.The loop checks


divisibility from 2 to sqrt(num).If num % i == 0, then num is not prime.If no
divisors are found, the number is prime.
1. Wildcard (*, ?) : ls *.sh # Lists all shell script files
Example Output : Enter a number: 7
ls file?.txt # Matches file1.txt, file2.txt
7 is Prime
2. Logical Operators (&&, ||) : mkdir newdir && echo "Directory created" # Runs
second command if mkdir succeeds 3. Check Armstrong Number : Script:

rm missingfile || echo "File not found" # Runs second command if rm fails #!/bin/bash

3. Redirection (>, >>, <) : echo "Hello" > output.txt # Overwrites file with "Hello" echo "Enter a number:"

echo "World" >> output.txt # Appends "World" to file read num

sort < names.txt # Sorts content of names.txt sum=0; temp=$num; n=${#num}

4. Pipes (|) : ls -l | grep ".txt" # Lists only .txt files while [ $temp -gt 0 ]; do

5. Quoting (" ", ' ', ` `) : echo "Today is $(date)" # Expands command digit=$((temp % 10))

echo 'Today is $(date)' # Treats as plain text sum=$((sum + digit ** n))

6. Background Execution (&) : sleep 10 & # Runs sleep command in the temp=$((temp / 10))
background

done
**Shell script for checking :

[ $sum -eq $num ] && echo "$num is Armstrong" || echo "$num is Not
1. Check Even or Odd : Script: Armstrong"

#!/bin/bash Explanation : An Armstrong number is a number where the sum of its digits
raised to the power of the number of digits equals the number itself.The script
echo "Enter a number:" extracts each digit, raises it to the power of n (total digits), and adds it to sum.If
sum == num, then it’s an Armstrong number.
read num
Example Output : Enter a number : 153
[ $((num % 2)) -eq 0 ] && echo "$num is Even" || echo "$num is Odd"
153 is Armstrong
Explanation : read num → Reads a number from the user.
4. Check Palindrome Number : Script:
$((num % 2)) → Checks if the remainder when divided by 2 is 0.
#!/bin/bash echo "First Argument: $1"

echo "Enter a number:" echo "Second Argument: $2"

read num echo "All Arguments: $@"

[ "$num" -eq "$(echo "$num" | rev)" ] && echo "$num is Palindrome" || echo echo "Total Number of Arguments: $#"
"$num is Not Palindrome"
Run the script with arguments : bash args.sh Hello World
Explanation : A palindrome number reads the same forward and backward.rev
command reverses the number.If num == reversed(num), then it’s a palindrome. Output : Script Name: args.sh

Example Output : Enter a number : 121 First Argument: Hello

121 is Palindrome Second Argument: World

5. Find Factorial : Script: All Arguments: Hello World

#!/bin/bash Total Number of Arguments: 2

echo "Enter a number:" Explanation : $0 → Script name

read num $1, $2, ... → Positional arguments

fact=1 $@ → All arguments as a list

for ((i = 1; i <= num; i++)); do fact=$((fact * i)); done $# → Number of arguments

echo "Factorial of $num is $fact" 2. Retrieving Return Values from Functions : Shell functions return values using
echo or return. Method 1: Using echo (Recommended) : Functions in shell scripts
Explanation : Factorial of n is n! = n * (n-1) * (n-2) ... * 1.Loop runs from 1 to num, do not return values like other programming languages. Instead, they print the
multiplying each value.The final factorial is printed. value, which can be captured using command substitution $( ).

Example Output : Enter a number: 5 Example : #!/bin/bash

Factorial of 5 is 120 sum_numbers() {

6. Concatenate Two Files : Script: sum=$(( $1 + $2 ))

#!/bin/bash echo $sum

echo "Enter two filenames to merge:" }

read file1 file2 result=$(sum_numbers 5 3)

cat "$file1" "$file2" > merged.txt && echo "Files merged into 'merged.txt'" echo "Sum is: $result"

Explanation : read file1 file2 → Reads two file names.cat "$file1" "$file2" > Output : Sum is: 8
merged.txt → Merges contents into a new file merged.txt.&& echo "Files
merged" → Displays success message if merge is successful. Method 2: Using return (Only for Status Codes) : The return statement only
returns an exit status (0-255).
Example Output : Enter two filenames to merge:
Example : #!/bin/bash
file1.txt file2.txt
check_even() {
Files merged into 'merged.txt'
[ $(( $1 % 2 )) -eq 0 ] && return 0 || return 1
Passing Arguments to a Shell Script & Retrieving Return Values from Functions :
}
1. Passing Arguments to a Shell Script : When running a shell script, you can pass
arguments directly in the command line. check_even 10

Example: Passing Arguments : Create a script args.sh: if [ $? -eq 0 ]; then

#!/bin/bash echo "Even Number"

echo "Script Name: $0" else


echo "Odd Number" command2 takes this output as input.

fi command3 can further process the output.

Output : Even Number 1. Basic Pipe Usage : Example:

Explanation : $? captures the exit status of the last executed command. ls -l | less

return 0 → Success, return 1 → Failure. Explanation : ls -l → Lists files in long format.

Redirection in Linux – Redirection in Linux allows you to change the input and less → Displays output page by page.
output sources for commands. It controls how data flows between the terminal,
files, and programs. This is useful when there are many files and you want to scroll through them.

1.Input Redirection (<) : By default, commands read input from the keyboard
(stdin). The < operator tells the command to read input from a file instead.

Example : sort < numbers.txt

Explanation : Reads the contents of numbers.txt.Sorts them in ascending


order.Displays the sorted output on the screen.Without <, we would need to
manually enter numbers, making the command interactive.

2. Output Redirection (> and >>) : By default, commands display output on the
screen (stdout). The > and >> operators redirect this output to a file.

Overwrite Output (>) : The > operator replaces existing file content.

Example : ls > filelist.txt

Explanation : Saves the list of files in filelist.txt.If filelist.txt already exists, it


overwrites it

Append Output (>>) : The >> operator adds new output to the file without
deleting the existing content.

Example : date >> log.txt

Explanation : Appends the current date to log.txt. Keeps previous data intact

3. Error Redirection (2>, 2>>) : By default, error messages (stderr) are displayed
on the screen. We can redirect them to a file instead.Redirect Errors to a File
(2>)The 2> operator saves only error messages into a file.

Example : ls nonexistentfile 2> error.log

Explanation : Since nonexistentfile doesn’t exist, an error is generated.The error


is stored in error.log instead of appearing on the screen.

Append Errors to a File (2>>) : The 2>> operator adds error messages to an
existing file without deleting old errors.

Example : ls anotherfile 2>> error.log

Explanation : If an error occurs, it is added to error.log without removing


previous errors.

What is Piping : Piping (|) is a method in Linux to send the output of one
command as the input to another command. This helps in chaining multiple
commands together to process data efficiently.

How Does Piping Work : Without pipes: We store output in a file and then use it
as input for another command.With pipes: We directly pass output from one
command to another.

Syntax : command1 | command2 | command3

command1 generates output.

You might also like