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

LINUX BASICS

The document provides an overview of essential Linux commands for file and directory management, including ls, cd, mkdir, rmdir, touch, rm, cp, and mv, along with their options and examples. It also covers user and group management, detailing user types, commands for adding, modifying, and deleting users and groups, as well as file permissions and ownership. Additionally, it introduces advanced file operations and text processing tools like grep, awk, and sed, emphasizing the use of the find command for searching files based on various criteria.

Uploaded by

ibrahimdazeen
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)
5 views

LINUX BASICS

The document provides an overview of essential Linux commands for file and directory management, including ls, cd, mkdir, rmdir, touch, rm, cp, and mv, along with their options and examples. It also covers user and group management, detailing user types, commands for adding, modifying, and deleting users and groups, as well as file permissions and ownership. Additionally, it introduces advanced file operations and text processing tools like grep, awk, and sed, emphasizing the use of the find command for searching files based on various criteria.

Uploaded by

ibrahimdazeen
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
You are on page 1/ 94

1.

DIRECTORY LISTING (LS)


Search for help for the ls command
ls --help
man ls
SYNOPSIS

ls [OPTION]... [FILE]...

OPTIONS
ls -l
ls -a
ls -r
ls -R
ls -S
ls -t
ls --color=no
ls --color=yes

Examples:

ls -l - list files in long format


ls -a - list all files, including hidden
ls -r - list files in reverse order
ls -R - list files recursively
ls -S - list files sorted by size
ls -t - list files sorted by modification time
ls --color - list files with colorized output

2. Change Directory cd
Search for help for the ls command

Note: The cd command is used to change the current working directory, and it
does not have many options like other commands. However, it can be used with
various arguments to navigate through directories.

cd --help
man cd

RELATIVE AND ABSOLUTE PATH

Path means a position in the directory tree.


To express a path, you can use relative path or absolute path.
In relative path expression, the path is not defined uniquely, depends on your
current path.
In absolute path expression, the path is defined uniquely, does not depend on
your current path

Absolute Path

Begin with a forward slash


Complete "road map" to file location
Can be used anytime you wish to specify a file name

cd ../subdir - change to subdir in parent directory


cd ~user - change to another users home directory
cd ~/Documents - change to Documents directory in home

Relative Path

Do not begin with a slash


Specify location relative to your current working directory
Can be used as a shorter way to specify a file name

cd /path/to/dir - change to absolute path directory


cd /home/kali/Desktop
cd /etc

Examples:

cd ~ - change to home directory


cd .. - change to parent directory
cd / - change to root directory
cd - - change to previous directory
cd . - change to current directory
cd ~/Documents - change to Documents directory in home
cd ../subdir - change to subdir in parent directory
cd ~user - change to another user's home directory
cd /path/to/dir - change to absolute path directory
cd ./relative/path - change to relative path directory

3. PRINT WORKING DIRECTORY (pwd)

Check for manual page

man pwd
pwd --help

Examples:

`pwd
man pwd - show manual page Note: The pwd command is used to print the current
working directory, and it has only a few options to modify its output.

4. CREATE A DIRECTORY (mkdir)

Check for manual Page

man mkdir
mkdir --help

Examples:

mkdir -p /path/dir/dir/dir - create newdir and its parents if needed


mkdir -m 755 newdir - create newdir with permissions 755
mkdir -v newdir - create newdir with verbose output
mkdir --help - show help message
mkdir --version - show version information
mkdir -p -v newdir - create newdir and its parents verbosely
Note: The mkdir command is used to create new directories, and its options allow for
customization of the creation process.

5. REMOVE DIRECTORY (rmdir) Show help message

rmdir --helo
man rmdir

Examples:

rmdir -v directory - remove directory with verbose output


rmdir --help - show help message
rmdir --version - show version information
rmdir --ignore-fail-on-non-empty directory - ignore failure if directory is not
empty
rmdir -- directory - remove directory with end of options marker

Note: The rmdir command is used to remove empty directories, and its options allow
for customization of the removal process.

6. CREATING FILES (touch) Show help message


touch --help
man touch

Examples:

touch file - change access time only for file


stat file - display file stats
touch -a file - change access time only for file
touch -m file - change modification time only for file
touch -t 202201010000 file - set timestamp to Jan 1, 2022, 00:00
touch --help - show help message
touch --version - show version information

Note: The touch command is used to create a new empty file or update the timestamp
of an existing file.

7. REMOVE FILE (rm) Show help message

man rm
rm --help
Examples:

rm -i file - prompt before removing file


rm -f file - force removal without prompting
rm -d directory - remove directory only if it's empty
rm -v file - remove file with verbose output
rm --help - show help message
rm --version - show version information

Note: The rm command is used to remove files and directories, and its options allow for
customization of the removal process.

8. COPYING FILES (cp) Show help message

man cp
cp --help

Examples:

cp -r dir1 dir2 - copy dir1 and its contents to dir2 recursively


cp -i file1 file2 - prompt before overwriting file2 with file1
cp -v file1 file2 - copy file1 to file2 with verbose output
cp --help - show help message
cp --version - show version information Note: The cp command is used to copy
files and directories, and its options allow for customization of the copy process.

8. MOVE COMMAND (mv) Show help message

man mv
mv --help

Examples:

mv -i file1 file2 - prompt before overwriting file2 with file1


mv -v file1 file2 - move file1 to file2 with verbose output
mv --help - show help message
mv --version - show version information

Note: The mv command is used to move or rename files and directories, and its options
allow for customization of the move process.
COURSE: LINUX OPERATING SYSTEM TOPIC: USERS, GROUPS AND
PERMISSIONS INSTRUCTOR: ZAKARIYYA DAHURU MUSA

OBJECTIVES
Understand Linux users and group
Manage users and groups
Modify file permissions and ownership

USERS Users are entities that interact with with the system directly or indirectly, they are
identified by a unique username and user ID (UID) with associated permissions, group
memberships and resources.

TYPES OF USERS

Root User: This is a super user with unlimited privileges and access to all system
resources. username = root
System Users: Created by the system for specific purposes such as:
Daemon users e.g. http, ftp which can be use to run system services and
daemons
System Service users: Users that manage system services e.g. MySQL
Regular Users: account created for individual people or applications with limited
privilege's and access to system resources.
Group users: Members of a group sharing common permissions and access to
resources

USERS CHARACTERISTICS

username - Unique identifier for each user


user ID (UID) - Numeric identifier for each user
Group ID (GID) - Numeric identifier for each user's primary group
Home directory - Default directory for each user
Password - account password
Shell - user's interactive terminal shell

USER COMMANDS

useradd - create a new user


usermod - Modify an existing user
userdel - Delete an existing user

GROUPS A group is a collection of users who share common permissions, access rights,
and resources. It helps manage user permissions and access control.
Group name - Unique identifier for the group
Group ID (GID) - Numeric identifier for the group
Members - users who belong to the group
Permissions - Access rights and priviledges assigned to the group

TYPES OF GROUP

Primary group - A user's default group, assigned when the user is created
Secondary group - Additional groups a user belongs to , providing extra permissions

BENFIT OF GROUPS

Simplified user management


Efficient permission management
Improve access control

GROUP COMMANDS

groupadd - create a new group


groupmod - Modify an existing groups
groupdel - delete a group
FILE PERMISSIONS Permissions determine what action a user, group members or
other users can perform on a file or directory.

TYPES OF PERMISSION

Read (r) - view the contents of a file


Write (w) - Modify or delete a file, create new files in a directory
Execute (x) - Run a file as a program or script or script in a directory

CATEGORIES OF USERS THAT CAN HAVE PERMISSION

Owner (u) - The user who created the file or directory


Group (g) - Members of the group
Other (o) - All other users on the system
PERMISSION NOTATION

rwx = read, write and execute


rw- = read and write
--x = execute

PERMISSION COMMAND

chmod - modify file permissions


chown - change ownership of a file
chgrp - change group of a file or directory

CHANGING PERMISSION Using Number Notation


x = 1
w = 2
wx = 3
r = 4
rx = 5
rw = 6
rwx = 7

example
chmod 655 filename = rw,rx,rx

Using Letters

u = user
g = group members
o = other users

chmod u=rw, g=rw, o=r


PRACTICAL EXERCISES - FILE AND DIRECTORY PERMISSION

Create a file file.txt


change its permission to owner = rwx , group = rx , others = r

chmod 754 file.txt - using numbers


u=rwx,g=rx,o=r file.txt - using letters
ls -l
Changing ownership - user

chown user1 file.txt


Changing ownership - group

chgrp <groupname> <file-name>


PRACTICAL EXERCISES - USERS AND GROUP Adding users

sudo adduser user1 - interactive


sudo userdd user2 - not interactive

Check the confirmation of user's creation

id user2
Deleting a user

sudo userdel <user2>

Creating multiple user's account from a file


username:password:UID:GID:GECOS:home_directory:shell

STEPS

create text file new_users


input user's information per line

user1:password1:1002:1002::/home/user2:/usr/bin/zsh
user2:password2:1003:1003::/home/user3:/usr/bin/zsh
user3:password3:1004:1004::/home/user4:/usr/bin/zsh

run the newuser command and redirect to the file newusers < new_users
Check existing users

getent passwd
who

\
GROUP MANAGEMENT Adding a new group

sudo groupadd <group_name> = add a group


sudo groupadd -g <GID> <groupname> = add a user with specified group ID

Check existing groups

getent group
Deleting a group

groupdel <group_name>
getent group
Add user to a specific group

sudo groupadd AIOVTI = Add a group


sudo usermod -aG <group_name> <user> = add user to a group
sudo usermod -rG <group_name> <user> = remove a user from a group
id <user> = check user creation confirmation
ADVANCE USER MODIFICATION

sudo usermod -u <UID> <user> = new user id


sudo usermod -L <user> = Lock user account
sudo usermod -U <user> = unlock user account
sudo usermod -l <user> = change login user name
sudo usermod -g <GID> <user> = change group id
sudo usermod -s <user> = changer user shell
sudo usermod -f "full name" = change user's full name
sudo usermod -c "comment" = add comment for a user
sudo passwd <user> = chnager user's password
ADVANCE GROUP MODIFICATION

sudo groupmod -g <GID> <group_name> = new group id


sudo groupmod -n <new_name> <group_name> = new group name
sudo groupmod -aU <user> <group_name>
COURSE: LINUX OPERATING SYSTEM TOPIC: ADVANCE FILE OPERATION AND
TEXT PROCESSING WEEK: FOUR INSTRUCTOR: ZAKARIYYA DAHURU MUSA

OBJECTIVES
Perform advanced file operations.
Use text processing tools and commands.

ADVANCE FILE OPERATION AND PROCESSING Advanced file operations refer to


complex file management tasks that go beyond basic operations like creating, deleting,
and copying files.

File Operations

Creation: Creating a new file or directory


Deletion: Removing a file or directory
Copy: Copying a file or directory to another location
Move: Moving a file or directory to another location
Rename: Renaming a file or directory
Search: Finding files based on criteria like name, size, or modification time

Text Processing

grep: Searching for patterns in text


awk: Pattern scanning and processing
sed: Stream editing

File Editing: Modifying file contents using editors or commands like sed

Key Commands and Tools

find: Searching for files based on criteria


grep: Searching for patterns in text
awk: Pattern scanning and processing
sed: Stream editing

TYPES OF TEXT EDITORS

GUI
mousepad
CLI
nano
gedit
vim
USING find COMMAND The find command is a powerful tool in Linux and Unix-like
operating systems that allows you to search for files and directories based on various
criteria such as name, type, user etc.

SYNOPSIS find path options expression

Components:

Path: The directory path where the search starts. If omitted, the current directory is
used.
Options: Modifiers that affect the search behavior, such as -name, -type, -size, etc.
Expression: The search criteria, such as a filename, size, or modification time.

find . -name "file.txt" = "file.txt" in the current directory and


subdirectories.

find / -type f -size +1M = files larger than 1MB in the entire file
system.

find . -mtime -1 = find . -mtime -1: files modified in the last 24 hours
in the current directory and subdirectories.
ADVANCE options FOR find

-name: Search for files by name.

-type: Search for files by type (e.g., d for directories, f for files).
-size: Search for files by size.

-mtime: Search for files by modification time.

Note:
-mtime -1 means "less than 1 day ago" (i.e., in the last 24 hours)
-mtime +7 means "more than 7 days ago"
-mtime 3 means "exactly 3 days ago"

-atime: Search for files by access time.

Note:

-atime -1 means "less than 1 day ago" (i.e., in the last 24 hours)
-atime +7 means "more than 7 days ago"
-atime 3 means "exactly 3 days ago"

-ctime: Search for files by creation time.


Note:

-ctime -1 means "less than 1 day ago" (i.e., in the last 24 hours)
-ctime +7 means "more than 7 days ago"
-ctime 3 means "exactly 3 days ago"

-perm: Search for files by permissions.

-user: Search for files by owner.


-group: Search for files by group.
-delete: Delete the found files.
-empty: Search for empty files or directories.
USING grep COMMAND The grep command is a powerful search tool in Linux and
Unix-like operating systems. It allows us to search for patterns within files or output of
commands. The name "grep" comes from the phrase "global regular expression
print".

SYNOPSIS grep options pattern file(s)

options are optional flags to modify the search behavior.


pattern is the regular expression or string to search for.
file(s) is the file(s) to search in.

Examples

- grep "hello" file.txt : Search for the string "hello" in file.txt

- grep -i "error" log.txt : Search for the string "error"in log.txt

- grep -r "pattern" directory/ : Search for the string "pattern"


recursively in the directory and its subdirectories

grep can also be used with pipes (|) to search output of other commands:

ls -l | grep "file.txt" : Search for the string "file.txt" in the output


of the ls -l command
ADVANCE options FOR grep COMMAD

-r : Search recursively in directories

Other Options

-q : Quiet mode (don't output anything, just exit status)


-s : Silent mode (don't output error messages)

-o : Print only the matched parts of the lines


USING awk COMMAND awk is a powerful tool for text processing, offering a wide
range of features for:

Text filtering: Select specific lines or fields based on conditions.


Text transformation: Modify or format text, such as converting case or rearranging
fields.
Text extraction: Extract specific fields or data from text files.

TERMS

1. Field separator: The default field separator is whitespace


2. Field numbering: Fields are numbered starting from 1. $1 refers to the first field, $2
refers to the second field, and so on.
3. Field access: You can access fields using the $ symbol followed by the field
number. For example, $1 prints the first field, $2 prints the second field, etc.
4. Field manipulation: You can perform operations on fields, such as printing,
concatenating, or modifying them.

FIELD EXPLANATION A LINE

A FIELD

Examples

PRINT THE FIRST FIELD OF THE FIRST LINE


awk 'NR==1 {print $1}' numbers = print the first field of the first
line

```bash
awk '{print $1}' file.txt = prints the first column (field) of each line
in file.txt

awk '/AIVTIC/ {print $0}' file.txt = This prints entire lines from
file.txt containing the string "AIVTIC"
awk '{print $1 "," $2 "," $3}' file.txt = This prints the first three
fields of each line in file.txt, separated by commas.

CONCATENATING

awk '{print $1 $2}' - Concatenates the first and second fields without a
separator.
awk '{print $1 "." $2}' - Concatenates the first and second fields with
a period in between.
MODIFYING

awk '{ $1 = "AIVTIC"; print $0 }' - Replaces the first field with
"AIVTIC" and prints the entire line.
awk '{ $2 = $2 + 10; print $0 }' - Increments the second field by 10 and
prints the entire line.

ARITHMETIC OPERATION

awk '{ $1 = $2 + $3; print $0 }' - Sets the first field to the sum of
the second and third fields and prints the entire line.
awk '{ $2 = $1 * 2; print $0 }' - Multiplies the second field by 2 and
prints the entire line.
STRING OPERATION

awk '{gsub(/1/, "new_number", $1); print $0}' - Replaces "1" with


"new_number" in the first field and prints the entire line.
awk '{print length($1)}' - Prints the length of the first field.
CONDITIONAL STATEMENT

awk '{if ($2 < 10) $2 = 10; print $0}' - Sets the second field to 10 if
it's less than 10 and prints the entire line.

USING sed COMMAND sed (Stream Editor) is a powerful command-line text


processing tool

USE CASES

Text replacement
Text deletion
Text insertion

TEXT REPLACEMENT

sed 's/C24/INTERNS/' sed_file = Replaces the first occurrence of "C24"


with "INTERNS" in each line

sed 's/C24/INTERNS/g' sed_file = Replaces all occurrences of "C24" with


"" in each line.
TEXT DELETION

sed '/HI/d' sed_file = Deletes lines containing "HI"


TEXT INSERTION

sed 'i\AIVTIC' sed_file = Inserts "AIVTIC" before each line.


COURSE: LINUX OPERATING SYSTEM TOPIC: PACKAGE MANAGEMENT WEEK:
ONE INSTRUCTOR: ZAKARIYYA DAHURU MUSA
OBJECTIVES

Understand Linux package managers.


Install, update, and remove software packages.

A package manager is a utility that automates the installation, update, and removal of
software packages, making it easier to maintain and configure your Linux system. It acts
as a central repository for software packages, allowing you to:

Update existing packages to the latest versions, ensuring you have the latest
security patches and features.
Install new software packages with ease, ensuring dependencies are resolved and
conflicts are avoided.
Remove unwanted packages, freeing up disk space and reducing clutter.

Most used package managers

APT (Advanced Package Tool) for Debian-based distributions (e.g., Ubuntu)


YUM (Yellowdog Updater, Modified) and DNF (Dandified YUM) for Red Hat-based
distributions (e.g., CentOS, Fedora)
PACKAGE UPDATE Debian-based systems (apt)

Open a terminal and run the command: sudo apt update


Enter your password to authenticate
The package lists will be updated, showing the latest versions of packages

sudo apt update

Red Hat-based systems (yum)

Open a terminal and run the command: sudo yum update


Enter your password to authenticate
The package lists will be updated, showing the latest versions of packages

sudo yum update

PACKAGE INSTALLATION Debian-based systems (apt)

Open a terminal and run the command: sudo apt install package name
Enter your password to authenticate
The software package will be installed

sudo apt install <package name>

Red Hat-based systems (yum)

Open a terminal and run the command: sudo yum install


Enter your password to authenticate
The software package will be installed

sudo yum install <package name>

REMOVING PACKAGE Debian-based systems (apt)

Open a terminal and run the command: sudo apt remove package name
Enter your password to authenticate
The software package will be removed

sudo apt remove <package name>


Red Hat-based systems (yum)

Open a terminal and run the command: sudo yum remove package name
Enter your password to authenticate
The software package will be removed

sudo yum remove <package name>

PACKAGE UPGRADE Debian-based systems (apt)

Update the package list: sudo apt update


Upgrade all packages: sudo apt full-upgrade
Upgrade a specific package: sudo apt install --only-upgrade package name

sudo apt full upgrade = complete upgrade


sudo apt install --only-upgrade <package name>

Red Hat-based systems (yum)

Update the package list: sudo yum check-update


Upgrade all packages: sudo yum update
Upgrade a specific package: sudo yum update package name

sudo yum check-update


sudo yum update
sudo yum update <package name>

ADDITIONAL (apt) OPTIONS

- purge: Remove a package and its configuration files.


- search: Search for a package.
- show: Show information about a package.
- list: List all packages or packages matching a pattern.

PRACTICAL EXCERCISE (apt)

sudo apt update

sudo apt upgrade


Listing Packages

sudo apt list

Searching for a package

sudo apt search web browser


sudo apt search editor | grep gedit
Package Installation

sudo apt install gedit


Package removal

sudo apt remove gedit


sudo apt install vlc

REMOVE VLC

sudo apt remove vlc


USING WGET COMMAND wget is a command-line utility for downloading files from the
internet. It retrieves files from a web server using HTTP, HTTPS, or FTP protocols. wget
supports downloading multiple files, resuming interrupted downloads, and saving files
with a specific name.

wget http://testphp.vulnweb.com/login.php

Downloading packages from GitHub

Navigate to the GitHub repo and copy the link


Open your terminal and paste it

git clone https://github.com/notepad-plus-plus/notepad-plus-plus.git


COURSE: LINUX OPERATING SYSTEM TOPIC: SHELL SCRIPTING BASICS WEEK:
ONE INSTRUCTOR: ZAKARIYYA DAHURU MUSA
Scripting is a form of programming where you write a series of commands or instructions
to automate tasks on a computer. scripting is usually interpreted, meaning the script is
read and executed directly by an interpreter.

BENEFITS OF SCRIPTING

Automate repetitive tasks: Perform tasks without human intervention, saving time
and reducing errors.
Simplify complex processes: Break down intricate tasks into manageable, step-
by-step instructions.
Increase productivity: Focus on high-priority tasks while scripts handle routine or
mundane work.
Improve accuracy: Reduce human error by ensuring tasks are executed
consistently and correctly.
Enhance flexibility: Easily modify or update scripts as needs change, without
affecting underlying systems.
Configuration management: Scripts can be used to configure software
environments, set up systems, and manage application deployment
System Admin: System administrators use scripts to manage user accounts,
monitor system health, automate updates, and handle other administrative tasks.
This reduces the workload and ensures consistency across the systems they
manage.

SHELL SCRIPT A shell script is a computer program designed to be run by the


Unix/Linux shell which could be one of the following:

The Bourne Shell


The C Shell
The Korn Shell
The GNU Bourne-Again Shell

A shell is a command-line interpreter and typical operations performed by shell scripts


include file manipulation, program execution, and printing text. Shell scripts have several
required constructs that tell the shell environment what to do and when to do it. Of
course, most scripts are more complex than the above one.

The shell is, after all, a real programming language, complete with variables, control
structures, and so forth. No matter how complicated a script gets, it is still just a list of
commands executed sequentially.

Note all the scripts would have the .sh extension

CREATING A SIMPLE SCRIPT

Open a text editor CLI or GUI


Declare your shebang - #!/bin/sh
Write your scripts and line of codes, save it
Make it executable
run it

EXECUTING A SCRIPT

Always use sudo to run scripts


Make sure it has an executable permission

sudo bash ./simple_script.sh OR sudo ./simple_script.sh

#!/bin/sh
echo "Welcome to AIOVTI?"
read student
echo "Hello, $student"

#!/bin/sh This tells the system that the commands that follow are to be executed by
the Bourne shell. it's called a shebang because the # symbol is called a hash, and the !
symbol is called a bang.

COMMENTS A good script must have comments for readability, we use # to declare
comments in scripting. A comment is not executed by the interpreter. It gives information
about a line of code or the entire script.
#!/bin/sh

# Welcome message
echo "Welcome to AIOVTI?"

# Collect student name


read student

# Display student name with Hello


echo "Hello, $student"

VARIABLES A variable is a container that allows us to store data from a user input or by
declaring it. A variable name can have:

Letters and numbers and underscore


It cannot start with a number or special characters except underscore

VALID VARIABLES

_MUSA
AIOVTI_A
VAR_1
VAR_2

INVALID VARIABLES
2_MUSA
-VARIABLE
@MUSA
VAR_A!

TYPES OF VARIABLES

Scalar variables: Store a single value


Array variables: Store multiple values
Integer variables: Store whole numbers, e.g., age=30
String variables: Store text values, e.g., name="John Doe"
Local variables: Defined inside a function, only accessible within that function
Global variables: Defined outside a function, accessible from anywhere in the
script
Read-only variables: Declared with read-only, cannot be modified
SCALAR VARIABLES
name="John Doe"

ARRAY VARAIBLES
colors=("red" "green" "blue")

INTEGAR VARIABLES
Age=20

STRING VARIABLES
Batch="Batch C24

LOCAL VARIABLES
local greetings="Hello, World!"

GLOBAL VARIABLES
greetings="Hello, World!"

READONLY VARAIBLES
readonly PI=3.14
SPECIAL VARIABLES

#!/bin/bash

# Print the name of the script itself


echo "Script Name: $0"

# Print process ID of the script


echo "Process ID: $$"

# Print length of a parameter


param="Hello World"
echo "Length of parameter: ${#param}"

# Remove shortest prefix matching pattern


echo "${param#Hello }"

ARITHMETIC OPERATIONS
+ (Addition) Adds values on either side of the operator

- (Subtraction) Subtracts right hand operand from left hand operand

* (Multiplication) Multiplies values on either side of the operator

/ (Division) Divides left hand operand by right hand operand

% (Modulus) Divides left hand operand by right hand operand and


returns remainder

= (Assignment) Assigns right operand in left operand

== (Equality) Compares two numbers, if both are same then returns


true.

!= (Not Equality)

RELATIONAL OPERATOR Bourne Shell supports the following relational operators that
are specific to numeric values. These operators do not work for string values unless their
value is numeric.
STRING OPERATORS
FILE OPERATORS

CONDITIONAL STATEMENTS Conditional statements in bash are used to execute


different blocks of code based on conditions or tests which is very useful in decision
making.

IF STATEMENT

if condition; then
# code to execute if condition is true
fi

if [ $x -gt 10 ]; then
echo "x is greater than 10"
else
echo "x is less than or equal to 10"
fi

if [ $x -gt 10 ] || [ $y -lt 20 ]; then


echo "x is greater than 10 or y is less than 20"
fi

IF-ELSE STATEMENT
IF-ELSE STATEMENT
if condition; then
# code to execute if condition is true
else
# code to execute if condition is false
fi

if [ $x -gt 10 ] && [ $y -lt 20 ]; then


echo "x is greater than 10 and y is less than 20"
else
echo "x is not greater than 10 or y is not less than 20"
fi

IF-ELIF-ELSE STATEMENT

IF-ELIF-ELSE STATEMENT
bash
if condition1; then
# code to execute if condition1 is true
elif condition2; then
# code to execute if condition1 is false and condition2 is true
else
# code to execute if both conditions are false
fi

if [ $x -gt 10 ]; then
echo "x is greater than 10"
elif [ $x -eq 10 ]; then
echo "x is equal to 10"
else
echo "x is less than 10"
fi

LOOPS Loops are a fundamental concept in programming that allow you to execute a
block of code repeatedly for a specified number of times or until a certain condition is
met.

For loop:
#!/bin/bash

# Print numbers from 1 to 5


for i in {1..5}; do
echo "Number: $i"
done

BENEFITS OF LOOPING

Repeating tasks
Iterating over data structures
Implementing algorithms
Simplifying code

PRACTICAL EXERCISES

Write a script that uses variables and prints their values.

#!/bin/bash

# Declare and assign variables


name="John Doe"
age=30
city="New York"

# Print variable values


echo "Name: $name"
echo "Age: $age"
echo "City: $city"

# Declare and assign another variable


country="USA"

# Print the new variable value


echo "Country: $country"

Create a script with a loop that prints numbers from 1 to 10.

#!/bin/bash
# Loop from 1 to 10
for i in {1..20}
do
echo $i
done

Write a script with an if-else statement that checks if a file exists.

#!/bin/bash

# Specify the file to check


FILE="example.txt"

# Check if the file exists


if [ -f "$FILE" ]; then
echo "The file $FILE exists."
else
echo "The file $FILE does not exist."
fi

You might also like