0% found this document useful (0 votes)
25 views49 pages

Linux Commands and Shell Scripting

Uploaded by

aryan
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)
25 views49 pages

Linux Commands and Shell Scripting

Uploaded by

aryan
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

Operating Systems and

Linux Fundamentals
Comprehensive Guide to System Administration

Exploring operating system concepts, Linux architecture, commands, editors, permissions, and
shell environments
Introduction to Operating Systems
Understanding the foundation of computer systems management

Definition

System software that manages computer hardware, software resources, and provides common services for

applications.

Functions

An operating system serves as an intermediary between users and computer hardware, managing processes,

memory, file systems, and device drivers. It provides a platform for applications to run, ensures system security,

handles multitasking, and facilitates user interaction through interfaces. Key functions include resource

allocation, process scheduling, memory management, and providing APIs for software development.
Types of Operating Systems
Classification and Characteristics

Mobile Operating Systems

Specialized OS designed for smartphones and tablets, featuring touch interfaces, app ecosystems,
power management, and connectivity features for portable devices.

Real-time Operating Systems


Systems with strict timing constraints, ensuring predictable response times for critical applications in
industrial control, medical devices, and aerospace systems.

Network and Embedded Systems

Network OS manages distributed computing resources across networks, while embedded OS runs on
specialized hardware with limited resources in IoT devices and appliances.
Linux vs Windows
Comparing two dominant operating system paradigms

Linux Windows

Proprietary operating system with user-friendly


Open-source Unix-like operating system known for
graphical interface and extensive software
stability, security, and flexibility. Features modular
compatibility. Offers integrated Microsoft ecosystem,
architecture, extensive customization options, and
gaming support, and business applications. Features
strong command-line interface. Supports multiple
automatic updates, hardware driver support, and
distributions, efficient resource utilization, and robust
familiar desktop environment but requires licensing
server capabilities with minimal licensing costs.
fees.
Architecture and Performance Comparison
Technical differences between Linux and Windows systems

Kernel Architecture Kernel Design

Monolithic kernel providing higher performance and direct Windows uses hybrid kernel balancing performance with
hardware access with efficient resource management. modularity, supporting various hardware configurations.

User Access
Security Model

Permission-based security with root access control, Administrator privileges with UAC (User Account
making it inherently more secure against malware. Control) providing security prompts for system changes.

File System File Management

Supports multiple file systems (ext4, Btrfs, XFS) with NTFS file system with case-insensitive naming,

case-sensitive naming and robust permissions. advanced features like compression and encryption.
Linux vs Windows Comparison Matrix
Key differences across various system aspects

Cost Customization
Linux offers extensive customization from kernel to
Linux is free and open-source with no licensing fees, while
desktop environments, while Windows provides limited
Windows requires paid licenses for commercial use. Linux
customization options. Users can modify Linux source
reduces total cost of ownership significantly for enterprises and
individual users seeking budget-friendly solutions. code and choose from hundreds of distributions tailored
to specific needs.
Software Performance
Windows has broader commercial software support
Linux typically uses fewer system resources and offers
and gaming compatibility, while Linux excels in
better performance on older hardware, while Windows
development tools and server applications. Linux
provides optimized performance for consumer applications
alternatives exist for most Windows software with
and gaming with extensive hardware driver support and
growing application ecosystem.
automatic optimization features.
=============================

=================
Linux Commands
=================

whoami : Logged in username

date : display current date

cal : display calendar

clear : to erase terminal content

pwd : To display present working directory

mkdir : to create directory

rmdir : to delete empty directory

Note: To delete non-empty directories we will use below command

$ rm -r <dirname>

cd : to change directory

ls : To display files & directories of present working directory

ls -l : display files and directories in alphabetical order

ls -lr : reverse of alphabetical order

(Try and explore more options)

touch : To create empty files

$ touch f1.txt f2.txt f3.txt

cat : create files with data , append data to existing file, display file
content

cat > filename (To create file with content)

cat >> filename (append data to existing file)

cat filename (display file content)

Note: cat command will display file data from top to bottom.

tac : reverse of cat

cp : It is used to copy data from one file to another file

$ cp f1.txt f2.txt

Note: To copy data from multiple files we need to use 'cat' command.

$ cat f1.txt f2.txt > f3.txt

rm : to delete file
$ rm filename

mv : to move / rename the file

$ mv old-name new-name

wc : word count

head : To display first 10 lines of file

$ head <filename> (default first 10 lines)

tail : To display last 10 lines of file

$ tail <filename> (default last 10 lines)

=======================
Text Editor in Linux
=======================

vi : visual editor

=> Using 'vi' command we can work with text editor

=> To open file we can use below command

$ vi ashokit.txt

insert mode : press 'i'

escape mode : press 'esc'

To save changes and close file => esc + :wq

Close file without saving changes => esc + :q!

=============
SED command
=============

=> SED stands for stream editor

=> SED is used for substitution/replacement

=> We can replace one word with another word using SED command without opening
the file

$ sed 's/aws/azure/' f1.txt

Note: By default, SED command will not make changes in the original file. It
will just print output on terminal.

$ sed -i 's/aws/azure/' f1.txt

=> Delete last line of the file


$ sed '$d' f1.txt

=> Delete 5th line of the file

$ sed '5d' f1.txt

=================
File Permissions
=================

=> We have 3 types of permissions

r : read
w : write
x : execute

=> File Permission contains 3 sections (total 9 characters)

1) User section (first 3 characters)


2) Group Section (middle 3 characters)
3) Others section (last 3 characters)

-rwxrwxrwx f1.txt

-rw-rw-r-- f2.txt

-r--rw-rw- f3.txt

dr-xr--rwx linux

=> To change file permission we have 'chmod' command in linux

+ : means add permission

- : means remove permission

chmod u+x f1.txt (adding execute permission for user)

=> File permissions we can manage with numeric numbers also

0 : No Permission

1 : Execute

2 : Write

3 : Execute + Write

4 : Read

5 : Read + Execute

6 : Read + Write

7 : Read + Write + Execute


=========================
Users & Groups in Linux
=========================

-> Linux is Multi User based OS

-> We can create Multiple User accounts in one Linux Machine

-> In Every Linux machine by default 'root' user account will be available

root user : super user

-> When we launch EC2 instance ( Amazon Linux AMI ) We got 'ec2-user' account
also.

-> For every user account one home directory will be available under /home
directory

ec2-user : /home/ec2-user

john : /home/john

=> We can get user account information by using 'id' command

$ id <username>

# switch to root user

$ sudo su (switch to root account)

$ sudo su - (switch to root user and point to root user home directory)

$ exit (exit from user account)

=======================================
Working with Users and Groups in Linux
=======================================

# Switch to root user

$ sudo su -

# Create New User account

$ useradd <uname>

# Set Password for User

$ passwd <uname>

# Display Users created

$ cat /etc/passwd

# Switch to user account

$ su <username>
# Delete user

$ userdel <uname>

Try and explore (user deletion + user home directory deletion)

# Display all groups available in Linux

$ cat /etc/group

# Create New Group

$ groupadd <group-name>

# Adding user to group

$ usermod -aG <group-name> <user-name>

# Remove user from the group

try and explore


# Display Users belongs to a group

try and explore


# Delete Group

$ groupdel <group-name>

# Change Group Name

$ groupmod -n <new-name> <old-name>

# change username

try and explore

# Change User password

$ passwd <uname>

==================
chown command
=================

=> This is used for ownership change

# change owner of the file

$ sudo chown <uname> <file-name/directory-name>

# We can change owner of the file using user-id also

$ sudo chown <UID> <file-name/directory-name>

# change owner-group

try and explore

# change owner-group using group-id

try and explore


# change owner and group at a time
try and explore

============================
locate and find commands
============================

=> 'locate' and 'find' commands are used for file search

=> In every linux machine locate db will be available which stores linux file
system details.

=> When we execute locate command it will fetch details from locate db.

=> 'find' command will do search in entire linux file system

=> 'find' command is used for more advanced search

# search for the files under home directory with given name
$ sudo find /home -name f1.txt

# find empty files under /home

$ sudo find /home -type f -empty

# find empty directories under /home

$ sudo find /home -type d -empty

=================================
Working with Zip files in Linux
=================================

# Create few files using touch command


$ touch f1.txt f2.txt f3.txt

# Veriy zip command is installed or not


$ zip -version

# Create zip with all text files


$ zip <zip-file-name> *.txt

# print content of zip file


$ zip -sf <filename>

# Add new file/directory to existing zip file


$ zip -r <zip-name> <file/directory>

# Delete a file from zip


$ zip -d <zip-file-name> <file-name-to-delete>

# Create zip file with encryption (setting password)


$ zip -e <zip-file-name> *.txt

# Unzip
$ unzip <zip-file-name>

ping : To check connectivity


$ ping www.gmail.com

$ ping 13.12.109.21

wget : To download files from internet using url

$ wget https://dlcdn.apache.org/tomcat/tomcat-10/v10.1.10/bin/apache-tomcat-
10.1.10-windows-x64.zip

curl : It is used to send HTTP Request to URL

$ curl 192.168.1.123

ifconfig : To get IP Address of our machine

$ ifconfig

==========================
Package Managers in Linux
==========================

-> Pkg managers are used to install softwares in linux machines.

apt : Advanced Package Tool (debian based distributions)

Ex: Ubuntu

Syntax : sudo apt install git

dpkg : It is underlying pkg manager used by 'apt'

yum : Yellowdog updater, modified (RED Hat based distributions)

Ex: RED Hat Linux, Amazon Linux, Cent OS linux

dnf : DANDIFIED YUM (It is replacing yum pkg manager in latest versions of
fedora and Cent OS)

==================================
How to install softwares in linux
==================================

# Install Java software


$ sudo yum install java

# Install java 1.8 version


$ sudo yum install java-1.8.0-openjdk

# Install Maven software


$ sudo yum install maven

# Install Git client


$ sudo yum install git

============================================
How to host static website in Amazon Linux
============================================

=> Website means collection of web pages

=> Websites are divided into 2 types


1) Static Website

2) Dynamic Website

=> Static websites will give same response for all users

=> Dynamic Websites will give response based on logged in user

Note: To run a website we need a web server

Ex: apache, httpd etc...

# update the packages


$ sudo yum update

# install httpd webserver


$ sudo yum install httpd

# Start the service


$ sudo service httpd start

Note: After starting httpd service, we can access our webserver using EC2-VM
public IP address.

Note: Enable HTTP Protocol in Security Group Inbound Rules to allow incoming
traffic.

=> After enabling HTTP port then access EC2-VM public IP in browser

URL : http://65.1.132.215/

http://65.1.132.215:80/

=> We can modify the content of our static website

$ cd /var/www/html

$ sudo vi index.html

Note: Write website content in index.html then save and close that file then
access
Ec2-vm public ip.

=======================
What is Grep Command
=======================

=> It stands for "Global Regular Expression Print"

=> The grep command is a powerful utility in Linux used for searching and
filtering text

=> The grep command searches for patterns or regular expressions in files or
input streams and displays lines that match the specified pattern.

Syntax: grep [options] pattern [file...]

# Pattern matching print


$ grep "keyword" file.txt
# Recursive print
$ grep -r "pattern" directory/

# Ignore case
$ grep -i "pattern" file.txt

# print line numbers


$ grep -n "pattern" file.txt

# Invert match (print files which are not matching given pattern)
$ grep -v "pattern" file.txt
Shell Programming Constructs
Building blocks of effective shell scripting

Overview

Shell programming provides powerful constructs for automating system tasks and creating

interactive scripts.

Core Elements

Shell programming includes variables for data storage, control structures for decision making

and iteration, functions for code reusability, operators for computations, and input/output

mechanisms for user interaction. These elements work together to create powerful automation

scripts that can handle file operations, text processing, system monitoring, and complex

workflow management in Unix and Linux environments.


Variable Declarations
Dynamic data storage in shell programming

Variable Syntax Variable Types


Variables in shell programming are dynamically Shell variables can store strings, integers, and

typed and declared without explicit type command outputs. Environment variables are

specification. Assignment uses the equals sign accessible system-wide using export command.

without spaces: variable_name=value. String Local variables exist only within the current

values should be enclosed in quotes for safety. shell session. Special variables like $0, $1, $2

Variables are referenced using the dollar sign represent script name and arguments. Built-in

prefix: $variable_name or ${variable_name} for variables include $HOME, $PATH, $USER for

complex expressions. system information.


Constant Declarations
Immutable values in shell

Readonly Variables Using readonly Command


Constants are created using the readonly command which prevents variable modification. Syntax:
readonly CONSTANT_NAME=value. Once declared, attempting to modify throws an error, ensuring data
integrity.

Environment Constants Using declare Command


The declare -r command creates read-only variables with optional type specification. Example: declare -
r PI=3.14159. This approach provides better control over variable attributes and scope.

Convention Based Constants Using Uppercase Naming


By convention, constants use uppercase names with underscores for readability. Examples: MAX_USERS=100,
CONFIG_FILE=/etc/app.conf. While not enforced, this convention improves code maintainability and clarity
for developers.
Shell Operators Overview
Essential operators for shell programming logic

Arithmetic Operators String Operators


Addition (+), subtraction (-), multiplication (*),
String equality (=, ==), inequality (!=), null check (-
division (/), modulus (%) for mathematical
z), non-null check (-n) for text processing.
operations.
Assignment Operators Logical Operators

Simple assignment (=), compound assignments (+=, AND (&&), OR (||), NOT (!) for combining multiple
-=, *=, /=) for variable manipulation. conditions in complex expressions.

Comparison Operators File Operators


Equality (-eq), inequality (-ne), greater than (-gt), File existence (-f), directory check (-d), readable (-r),
less than (-lt) for numerical comparisons. writable (-w), executable (-x) for file system
operations.
Operator Examples
Practical implementation of shell operators

Arithmetic Operations Comparison Examples

Arithmetic operations in shell require specific syntax for Comparison operators enable conditional logic in scripts.

proper evaluation. Using double parentheses: result=$((5 + Numerical comparison: if [ $age -ge 18 ]; then echo

3)) performs addition. The expr command: result=`expr 5 + \"Adult\"; fi checks age threshold. String comparison: if [

3` provides alternative arithmetic evaluation. For floating- \"$name\" = \"admin\" ]; then echo \"Administrator\"; fi

point operations, bc calculator is used: result=`echo \"5.5 validates user identity. File existence: if [ -f

+ 3.2\" | bc`. Variable arithmetic: counter=$((counter + 1)) \"/etc/passwd\" ]; then echo \"File exists\"; fi checks

increments values. Modulus operation: system files. Multiple conditions: if [ $score -gt 80 ] && [

remainder=$((number % 2)) checks for even/odd numbers. $attendance -ge 75 ]; then echo \"Pass\"; fi combines

criteria for complex evaluations.


Decision Making Statements
Controlling program flow with conditional logic

Purpose
Decision making statements allow programs to execute different code paths based on specific conditions and

user input.

Implementation

Shell provides multiple decision-making constructs including if-then-else statements for binary choices, nested

if statements for complex conditions, case statements for multiple options, and logical operators for combining

conditions. These constructs enable scripts to respond dynamically to different scenarios, validate user input,

check system states, and implement sophisticated program logic that adapts to varying runtime conditions and

environmental factors.
Decision Making Types
Available conditional constructs

If-Then-Else Statement for Binary Decisions


The fundamental conditional structure tests a single condition and executes different code blocks. Syntax: if [ condition ];
then commands; else commands; fi. Supports elif for multiple conditions in sequence.

Case Statement for Multiple Choice Selection


Efficient for handling multiple discrete values or patterns. Syntax: case $variable in pattern1) commands;; pattern2)
commands;; *) default;; esac. Supports wildcards and regex patterns for flexible matching.

Nested Conditionals for Complex Logic Structures


Combining multiple if statements within each other enables sophisticated decision trees. Allows for hierarchical condition
checking where inner conditions depend on outer condition results, enabling complex program flow control and detailed
validation logic.
If-Then-Else Statement Example

Implementation Details

This example demonstrates basic conditional logic using

numerical comparison. The -ge operator checks if the


"if [ $age -ge 18 ]; then echo \"You are eligible to age variable is greater than or equal to 18. The script
vote\"; else echo \"You are not eligible to vote\"; fi" provides different messages based on the condition

result. This pattern is commonly used for validation,

user access control, and system state checking in shell


— Basic Age Validation Script scripts and system administration tasks.
Advanced Decision Examples
Complex conditional logic implementations

Case Statement Nested Conditions


Nested if statements enable complex decision trees.
Case statements handle multiple discrete options
Example: if [ $user = "admin" ]; then if [ $password =
efficiently. Example: case $choice in 1) echo "Option
"secret" ]; then echo "Access granted"; else echo "Wrong
One";; 2) echo "Option Two";; 3) echo "Option Three";; *)
password"; fi; else echo "Unauthorized user"; fi. This
echo "Invalid choice";; esac. This structure is ideal for
approach allows for hierarchical validation where multiple
menu systems, command-line argument processing, and
criteria must be satisfied sequentially, enabling
handling user selections. Pattern matching supports
sophisticated access control and multi-step verification
wildcards and ranges for flexible input validation and
processes.
processing.
Loop Statements
Repetitive execution for automation and iteration

Overview

Loop statements enable repetitive execution of code blocks until specific conditions are met or collections are processed.

Applications

Loops are essential for processing arrays, iterating through files, automating repetitive tasks, and handling user input validation. Shell

provides for loops for iterating over lists and ranges, while loops for condition-based repetition, and until loops for negative condition

checking. These constructs enable efficient batch processing, system monitoring scripts, and automated deployment procedures that

require repetitive operations across multiple resources or data sets.


Loop Types
Available iteration constructs

For Loop for List and Range Iteration


Processes predefined lists or ranges of values. Syntax: for variable in list; do commands; done. Supports range generation
with {1..10} and file globbing patterns for processing multiple files efficiently.

While Loop for Condition Based Repetition


Continues execution while condition remains true. Syntax: while [ condition ]; do commands; done. Ideal for reading files
line by line, monitoring system states, and implementing interactive menus with user input validation.

Until Loop for Negative Condition Checking


Executes until condition becomes true (opposite of while). Syntax: until [ condition ]; do commands; done. Useful for waiting
for resources, polling for file creation, and implementing retry mechanisms with timeout controls.
For Loop Example

Implementation Details

This example demonstrates a for loop iterating through

a numeric range from 1 to 5. Each iteration prints a


"for i in {1..5}; do echo \"Processing item $i\"; sleep 1; message with the current value and pauses for one
done" second using sleep command. This pattern is commonly

used for batch processing, creating numbered files,

— Range-based For Loop generating test data, and implementing progress

indicators in shell scripts and automation workflows.


While and Until Examples
Condition-based loop implementations

While Loop Until Loop

While loops continue execution based on true conditions. Until loops execute until condition becomes true. Example:
Example: counter=1; while [ $counter -le 5 ]; do echo attempts=0; until ping -c 1 google.com &> /dev/null; do
"Count: $counter"; counter=$((counter + 1)); done. This echo "Waiting for connection..."; attempts=$((attempts +
pattern is perfect for reading files line by line: while IFS= 1)); if [ $attempts -gt 10 ]; then break; fi; sleep 5; done.
read -r line; do echo "Processing: $line"; done < file.txt. This approach is ideal for waiting for services to start,
While loops are essential for monitoring system states, polling for file creation, and implementing retry
processing streaming data, and implementing interactive mechanisms with built-in timeout controls.
menus.
Nested Loops Example

Implementation Details

This example demonstrates nested for loops creating a

3x3 coordinate matrix. The outer loop controls rows

while the inner loop handles columns, producing


"for i in {1..3}; do for j in {1..3}; do echo \"($i,$j)\"; output like (1,1), (1,2), (1,3), (2,1), etc. This pattern is
done; done" valuable for processing multi-dimensional data,

generating test matrices, creating nested directory

— Matrix Generation Script structures, and implementing algorithms that require

nested iteration such as sorting and searching

operations.
Advanced Loop Examples
Complex iteration patterns and optimizations

File Processing Break and Continue

Loops excel at batch file operations. Example: for file in Loop control statements provide flow management. Break
*.txt; do if [ -f \"$file\" ]; then echo \"Processing $file\"; example: for num in {1..10}; do if [ $num -eq 5 ]; then
mv \"$file\" \"processed_$file\"; fi; done. This pattern break; fi; echo $num; done outputs 1-4. Continue
processes all text files in a directory, checking existence example: for num in {1..10}; do if [ $((num % 2)) -eq 0 ];
before operations. Advanced pattern: find /path -name then continue; fi; echo $num; done prints odd numbers
\"*.log\" -print0 | while IFS= read -r -d '' file; do echo only. These controls enable sophisticated filtering and
\"Analyzing $file\"; grep ERROR \"$file\" >> early termination in complex processing scenarios.
error_summary.txt; done for handling files with spaces.
Arrays
Structured data storage and manipulation

Array Declaration Array Access

Arrays store multiple values in indexed collections. Declaration Elements are accessed using array[index] syntax with ${array[0]}

syntax: array_name=(value1 value2 value3) creates an indexed notation. All elements: ${array[@]} or ${array[*]} returns complete

array. Individual assignment: array[0]="first" sets specific array. Array length: ${#array[@]} counts elements. Index ranges:

elements. Arrays support mixed data types and dynamic sizing. ${array[@]:start:length} extracts subarrays. Iteration: for element

Associative arrays use declare -A for key-value pairs with string in "${array[@]}" processes each element safely with proper

indices instead of numeric. quoting.


Array Operations
Essential array manipulation techniques

Array Creation and Initialization Methods

Arrays can be created using parentheses notation: fruits=(apple orange banana), through individual assignment:
colors[0]="red", or by reading from files: readarray -t lines < file.txt. Command substitution arrays: files=($(ls *.txt)) capture
command output as array elements.

Array Modification and Element Management


Adding elements: array+=(new_element) appends values. Removing elements: unset array[index] deletes specific positions.
Replacing elements: array[index]="new_value" updates existing positions. Concatenation: combined=("${array1[@]}"
"${array2[@]}") merges multiple arrays into one.

Array Iteration and Processing Patterns


Standard iteration: for item in "${array[@]}"; do echo "$item"; done processes all elements. Index-based: for i in
"${!array[@]}"; do echo "Index $i: ${array[i]}"; done shows positions. Filtering arrays with conditional processing enables
sophisticated data manipulation and validation workflows.
Basic Array Example

Implementation Details

This example demonstrates basic array creation and

access patterns. The array fruits is initialized with three

elements using parentheses notation. Individual


"fruits=(apple orange banana); echo \"First fruit: elements are accessed using index notation ${fruits[0]}
${fruits[0]}\"; echo \"All fruits: ${fruits[@]}\"" for the first element. The ${fruits[@]} syntax retrieves

all array elements for complete processing. This

— Simple Array Processing foundational pattern enables data collection, batch

processing, and structured information management in

shell scripts.
Advanced Array Examples
Complex array operations and real-world applications

Associative Arrays Array Processing


Associative arrays use string keys instead of numeric Advanced array manipulation enables powerful data
indices. Example: declare -A student_grades; processing. Example: numbers=(1 2 3 4 5); sum=0; for num
student_grades["John"]=85; student_grades["Alice"]=92; in "${numbers[@]}"; do sum=$((sum + num)); done; echo
student_grades["Bob"]=78; for student in "Sum: $sum". Array filtering: even_numbers=(); for num in
"${!student_grades[@]}"; do echo "$student: "${numbers[@]}"; do if [ $((num % 2)) -eq 0 ]; then
${student_grades[$student]}"; done. This structure is even_numbers+=("$num"); fi; done. These patterns
perfect for configuration management, database-like support statistical analysis, data transformation, and
operations, and mapping relationships where meaningful complex algorithmic implementations.
keys improve code readability and maintenance.
Array Manipulation Example

Implementation Details

This example demonstrates array creation from file

globbing and indexed iteration. The *.txt pattern

"files=(*.txt); for i in \"${!files[@]}\"; do echo \"File expands to all text files in the current directory, creating

an array. The ${!files[@]} syntax retrieves array indices,


$((i+1)): ${files[i]}\"; done"
allowing numbered display of files. This pattern is

essential for file management scripts, creating


— File Listing with Index Numbers
numbered menus, and processing files with positional

awareness in automation workflows.


Array Sorting and Searching
Advanced array algorithms and data manipulation

Array Sorting Array Searching


Searching arrays for specific values or patterns. Linear
Sorting arrays requires external tools or custom logic.
search: found=false; for item in \"${array[@]}\"; do if [[
Example using sort: IFS=$'\\n' sorted=($(sort <(printf
\"$item\" == \"$search_term\" ]]; then found=true; break;
'%s\\n' \"${array[@]}\"))); for item in \"${sorted[@]}\"; do
fi; done. Pattern matching: matches=(); for item in
echo \"$item\"; done. Bubble sort implementation: for
\"${array[@]}\"; do if [[ \"$item\" =~ $pattern ]]; then
((i=0; i<${#arr[@]}; i++)); do for ((j=0; j<${#arr[@]}-1-i;
matches+=(\"$item\"); fi; done. These search patterns
j++)); do if [[ ${arr[j]} > ${arr[j+1]} ]]; then temp=${arr[j]};
support data validation, filtering operations, and
arr[j]=${arr[j+1]}; arr[j+1]=$temp; fi; done; done. These
conditional processing based on array content analysis.
techniques enable data organization and ordered

processing.
Functions
Reusable code blocks and modular programming

Function Syntax Function Benefits

Functions promote code reusability, reduce redundancy, and


Functions encapsulate reusable code blocks for better organization
improve script maintainability. They enable modular programming
and maintainability. Declaration syntax: function_name() {
approaches, facilitate testing and debugging, and support
commands; } or function function_name { commands; }. Functions
parameter passing for flexible implementations. Functions can be
accept parameters through $1, $2, etc. and return values using
sourced from external files, creating libraries of common utilities
return statement or echo for output capture. Local variables use
that enhance development productivity and code quality across
local keyword for scope control.
multiple scripts.
Function Types
Different function implementation patterns

Simple Functions for Basic Task Encapsulation


Basic functions perform single tasks without parameters. Example: backup_files() { cp *.txt backup/; echo \"Backup completed\"; }. These functions improve
code organization and provide simple automation for repetitive tasks requiring no customization.

Parameterized Functions for Flexible Operations


Functions accepting parameters enable flexible and reusable implementations. Example: greet_user() { echo \"Hello, $1! Today is $(date)\"; }. Parameters
$1, $2, etc. allow customization while maintaining consistent behavior patterns across different use cases.

Functions with Return Values for Data Processing

Functions can return values through echo or return statements. Example: calculate_sum() { local result=$(($1 + $2)); echo $result; }. This pattern enables
mathematical operations, data transformations, and result passing between different script components for complex processing workflows.
Basic Function Example

Implementation Details

This example demonstrates basic function creation and

invocation with parameter passing. The greet function

accepts one parameter ($1) representing the user's


"greet() { echo \"Hello, $1!\"; echo \"Welcome to name and displays a personalized welcome message.
Linux programming\"; }; greet \"John\"" Function calls use the function name followed by

arguments. This pattern is fundamental for creating

— Simple Parameterized Function reusable code blocks that can be customized through

parameters, improving script modularity and

maintainability.
Advanced Function Examples
Complex function implementations and design patterns

Recursive Functions Function Libraries

Functions can call themselves for recursive algorithms. Creating reusable function libraries improves code

Example: factorial() { if [ $1 -le 1 ]; then echo 1; else local organization. Example library file utils.sh: log_message() {

temp=$(factorial $(($1 - 1))); echo $(($1 * temp)); fi; }. echo \"[$(date)] $1\" >> logfile.txt; }; validate_email() { [[

Fibonacci sequence: fib() { if [ $1 -le 1 ]; then echo $1; else $1 =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$ ]];

echo $(($(fib $(($1-1))) + $(fib $(($1-2))))); fi; }. Recursive }. Source in scripts: source utils.sh; log_message \"Script

functions solve mathematical problems, tree traversal, and started\". Libraries enable consistent functionality across

nested data structure processing efficiently. multiple scripts, promoting code reuse and standardization

in development workflows.
Function with Return Value

Implementation Details

This example shows function return value handling

through command substitution. The add_numbers

"add_numbers() { local sum=$(($1 + $2)); echo $sum; function performs addition using local variables for

}; result=$(add_numbers 15 25); echo \"Sum: calculation and returns the result via echo. The calling

code captures the output using command substitution


$result\""
$(add_numbers 15 25). This pattern enables functions

to process data and return results for further use,


— Mathematical Function Implementation
supporting complex calculations and data

transformation workflows in shell programming.


Function Best Practices
Professional development and optimization techniques

Overview

Effective function development requires attention to error handling, documentation, and testing for robust implementations.

Implementation

Functions should validate input parameters, handle edge cases gracefully, and provide clear error messages. Include comprehensive

documentation with purpose, parameters, return values, and usage examples. Implement test cases to verify functionality under

normal and exceptional conditions. Use meaningful function names, local variables for scope control, and consistent return codes for

error handling. These practices ensure maintainable, reliable, and reusable code that follows professional development standards.
===================
Linux Architecture
===================

1) Applications

2) Shell

3) Kernal

4) Hardware

=> When we execute any command in linux then Shell will process our command execution.

=> Shell will verify command syntax is valid or not.

=> Shell will convert our command into 'kernel' understandable format

=> Kernel is responsible to communicate with Hardware components

=> Kernel is the mediator between Shell and Hardware.

=> Shell is mediator between 'user' and 'kernel'

# Print all shells of linux machine


$ cat /etc/shells

# Print default shell of linux machine


$ echo $SHELL

Note: We have '/bin/bash' as default shell.

============================
What is Shell Scripting ?
============================

=> Shell will act as mediator between Users and Kernel. Shell will convert commands into kernal
understandable format.

=> Scripting means executing set of commands using a file.

##### The process of executing set of commands available in the file using SHELL is called as
Shell Scripting #####

=> Shell Scripting is used to automate our daily routine works.

=> Shell Script file will have .sh extension

=> Below is the command to execute shell script file


$ sh <filename>

====================
Script-1 : work.sh
====================

#! /bin/bash

whoami
pwd
date

#### Run : sh work.sh ####

=====================
Script-2 : msg.sh
=====================

#! /bin/bash

echo 'Hello World'


echo 'Welcome to DevOps World'
echo 'DevOps is very intresting'

========================
Script-3 : NameDemo.sh
========================

#! /bin/bash

echo 'Enter Your Name'


read a
echo "Good Evening $a"

===================
Script-4 : Sum.sh
===================

#! /bin/bash

a=10
b=20

c=$(($a+$b))

echo "Sum is : $c"

============================
Script-5 : DynamicValSum.sh
============================

#! /bin/bash

echo "Enter First Number"


read a

echo "Enter Second Number"


read b

c=$(($a+$b))

echo "Result : $c"

============
Variables
============

=> Variables are used to store the data

=> Variables are key-value pairs

id = 101

gender = male

=> Variables are divided into 2 types

1) Environment Variables ( System Variables - Already Defined )

2) User Defined Variables (We will create these variables)

Note: To access value of variable we will use '$' symbol.

Ex: $SHELL $USER

=======================
Command Line Arguments
=======================

=> The arguments which we we will pass to script file at the time of execution.

Ex: sh demo.sh ashokit 30

=> We can access command-line args in script file like below

$# - No.of args

$0 - script file name

$1 - First Cmd arg

$2 - Second Cmd arg

$3 - Third Cmd Args

$* - All cmd args


============================
Script-6 : DynamicValSum.sh
============================

#! /bin/bash

result=$(($1+$2))

echo "Sum is : $(($1+$2))"

Run : sh DynamicValSum.sh 10 20

==================================================================

=> We have 2 options to pass dynamic values to shell script file

1) Using 'read' command

2) Using cmd args

==================================================================

1) Conditional Statements ( if - elif - else )

2) Loops ( for & while )

3) Functions

===========================
Conditional Statements
==========================

=> Conditional Statements are used to execute 'commands' one time based on condition

Ex : if - else / if - elif - else

Syntax:

if [ condition ]
then
statements
else
statements

=======================
Script-7 : if-else.sh
=======================

#! /bin/bash

echo "Enter Name"


read name

if [ $name == 'john' ]
then
echo "Hi"
else
echo "Bye"
fi

===============================
Script - 8 : if-elif-else.sh
===============================

#! /bin/bash

echo "Enter Name"


read name

if [ $name == 'john' ]
then
echo "Hi $name"

elif [ $name == 'smith' ]


then
echo "Hello $name"

else
echo "Bye $name"
fi

====================
Loops
====================

=> To print "hi" 5 times we will write script like below

echo "hi"
echo "hi"
echo "hi"
echo "hi"
echo "hi"

=> If we want to print "hi" for 1000 times, can we write echo for 1000 times ? Not recommended

=> To execute same command multiple times then we will use "Loops"

=> We have 2 types of loops

1) Range Based Loop ( Ex: for loop )

2) Conditional Based Loop ( Ex: while loop )

=> Print "hi" message 10 times (Here we know the range to print msg - we can use 'for' loop)

=> Print "good night" message till 10 PM (Here we don't range but we know condition - we can use
while loop)

=========================
Script-10 : for-loop1.sh
=========================

#! /bin/bash

for (( i=1 ; i<=10; i++ ))


do
echo "hi"
done

=========================
Script-11 : for-loop2.sh
=========================

#! /bin/bash

for (( i=1; i<=10; i++ ))


do
echo "$i"
done

============================
Script-12 : while-loop.sh
============================

#! /bin/bash

i=10
while [ $i -ge 1 ]
do
echo "$i"

let i--;
done

=====================
Functions / Methods
====================

=> Functions are used to perform some action / task

=> The big task can be divided into smaller tasks using functions

=> Using functions we can divide our tasks logically

=> Functions are re-usable

Syntax:
-------

# writing function
function functionName ( ) {

// function body
}
# calling function
functionName

=======================
Script - 13 : fun1.sh
=======================

#! /bin/bash

function welcome ( ) {

echo "this is line 1"


echo "this is line 2"
echo "this is line 2"

# calling function
welcome

You might also like