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

Lab Manual OS

These are List of Experiments Linux Installation and Virtual Machines Linux Basic Commands (Part 1) Linux Basic Commands (Part 2) Regular Expressions User Management Commands Introduction to Shell Programming Conditional Statements in Shell Programming Loops in Shell Programming Functions in Shell Programming Arrays and Strings Debugging Techniques in Shell Programming Scheduling Bash Scripts with cron Networking and Scripting Introduction to g++ and using fork system call
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Lab Manual OS

These are List of Experiments Linux Installation and Virtual Machines Linux Basic Commands (Part 1) Linux Basic Commands (Part 2) Regular Expressions User Management Commands Introduction to Shell Programming Conditional Statements in Shell Programming Loops in Shell Programming Functions in Shell Programming Arrays and Strings Debugging Techniques in Shell Programming Scheduling Bash Scripts with cron Networking and Scripting Introduction to g++ and using fork system call
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

International Islamic University, Islamabad

Faculty of Engineering & Technology


Department of Electrical and Computer Engineering

CS_301 L
Operating Systems Lab

Lab Manual

Subject Teacher:

Lab Instructor:

Prepared by:

Engr. Rashid Farid Chishti


Lecturer, Department of Electrical and Computer Engineering.
Faculty of Engineering and Technology.
International Islamic University, Islamabad.

i
Names of Group Members

Student
Name
Reg.
No.

Student
Name
Reg.
No.

Student
Name
Reg.
No.

Student
Name
Reg.
No.

ii
CS_301 L
Operating Systems Lab
Lab Manual

OBJECTIVE
The main objective of this is to understand the fundamental principles and
components of operating systems. Develop hands-on skills through
practical lab exercises to reinforce theoretical concepts.

CLO CLO Description DOMAIN PLO


01 Design algorithms related to OS Subsystems C5 02
using gcc compiler
02 Practice Linux Shell and interact with OS P3 05
Subsystems using Shell commands
03 Participate actively in performing the A2 09
procedure.

CLO: Course Learning Outcome.


PLO: Program Learning Outcome.

iii
Operating Systems Lab Rubrics
Name: Reg. No.: Signature: Instructor:

a) PSYCHOMOTOR (To be judged in the field/lab during experiment)


Level La La La Lab Lab
Sr. Level 2 Level 3 Level 4 Level 5 Lab Lab Lab Lab Lab Lab Lab Lab Lab
Criteria 1 Lab b b b 13 14
No. (25%) (50%) (75%) (100%) 1 3 4 5 6 7 9 10 11
(0%) 2 8 12
0 1.25 2.5 3.75 5 Weightage 5 5 5 5 5 5 5 5 5 5 5 5 5 5
Practical With few
Implementation/ With several With some Without
1 errors,
Arrangement of critical errors, errors, errors,
Absent incomplete Obtained
Equipment incomplete and complete complete
and not
not neat but not neat and neat
neat
Use of 0 0.5 1 1.5 2 Weightage 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Equipment or
Considerabl
2 Simulation/ Limited Some
Absent e Competence Obtained
Programming competence competence
competence
Tool

(b) COGNITIVE (To be judged on the copy of experiment submitted)


Level La La La Lab Lab
Sr. Level 2 Level 3 Level 4 Level 5 Lab Lab Lab Lab Lab Lab Lab Lab Lab
Criteria 1 Lab b b b 13 14
No. (25%) (50%) (75%) (100%) 1 3 4 5 6 7 9 10 11
(0%) 2 8 12
Algorithm Design 0 0.25 0.5 0.75 1 Weightage 1 1 1 1 1 1 1 1 1 1 1 1 1 1
or Data Record, Complete Complete Complete
3
Analysis and Absent Incorrect with some with few and Obtained
Evaluation errors errors Accurate

(c) AFFECTIVE (To be judged in the field/lab during experiment)


Level La La La Lab Lab
Sr. Level 2 Level 3 Level 4 Level 5 Lab Lab Lab Lab Lab Lab Lab Lab Lab
Criteria 1 Lab b b b 13 14
No. (25%) (50%) (75%) (100%) 1 3 4 5 6 7 9 10 11
(0%) 2 8 12
Level of 0 0.5 1 1.5 2 Weightage 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Participation &
Attitude to Some Good Encouraging
4 Rare sensible
Achieve Absent sensible sensible sensible Obtained
interaction
Individual/Group interaction interaction interaction
Goals

5 TOTAL OBTAINED MARKS (Out of 10):

iv
v
Table of Contents
Lab 1: Linux Installation and Virtual Machines............................................................................................
Lab 2: Linux Basic Commands (Part 1).......................................................................................................
Lab 3: Linux Basic Commands (Part 2).......................................................................................................
Lab 4: Regular Expressions........................................................................................................................
Lab 5: User Management Commands.......................................................................................................
Lab 6: Introduction to Shell Programming.................................................................................................
Lab 7: Conditional Statements in Shell Programming................................................................................
Lab 8: Loops in Shell Programming............................................................................................................
Lab 9: Functions in Shell Programming......................................................................................................
Lab 10: Arrays and Strings.........................................................................................................................
Lab 11: Debugging Techniques in Shell Programming...............................................................................
Lab 12: Scheduling Bash Scripts with cron.................................................................................................
Lab 13: Networking and Scripting..............................................................................................................
Lab 14: Introduction to g++ and using fork system call.............................................................................

vi
Lab 1: Linux Installation and Virtual Machines

Lab 1: Linux Installation and Virtual Machines


Objective: Learn how to install a Linux distribution on a
virtual machine.

Download Ubuntu from following website

https://ubuntu.com/download/desktop

 Click on [Download 24.04 LTS] 6G


System Requirement
 2 GHz dual-core processor or better
 4 GB system memory
 25 GB of free hard drive space
 Either a USB port or a DVD drive for the installer media
 Internet access is helpful

Virtual Box Installation


Download and install Oracle VM Virtual Box from the following website

https://www.virtualbox.org/wiki/Downloads

 Click on Windows hosts

1
Lab 1: Linux Installation and Virtual Machines

Create a new virtual machine


Click on menu Machine > New to create a new virtual machine. Fill in the appropriate
details:

Name: Name of OS and its version


Folder: This is where your virtual machines will be stored
ISO Path of OS installation image (.iso file)
Image:

Now Press Next Button

To enable the automatic install we need to prepopulate our username and password here in
addition to our machine name so that it can be configured automatically during first boot.

The default credentials are:


 Username: vboxuser
 Password: changeme
It is important to change these values since the defaults will create a user without sudo
access.

Ensure your Hostname has no spaces to proceed!

It is also recommended to check the Guest Additions box to install the default Guest
Additions ISO that is downloaded as part of VirtualBox. Guest additions enables a number of
quality of life features such as changing resolution and dynamic screen resizing so it is highly
recommended!

2
Lab 1: Linux Installation and Virtual Machines

In the next section we can specify how much of our host machine’s memory and processors
the virtual machine can use. For good performance it’s recommended to provide your VM
with around 8GB of RAM (although 4GB will still be usable) and 4 CPUs. Try to remain in
the green areas of each slider to prevent issues with your machine running both the VM and
the host OS.

Then we need to specify the size of the hard disc for the virtual machine. For Ubuntu we
recommend around 25 GB as a minimum. By default the hard disk will scale dynamically as
more memory is required up to the defined limit. If you want to pre-allocate the full amount,
check the ‘Pre-allocate Full Size’ check box. This will improve performance but may take up
unnecessary space.

3
Lab 1: Linux Installation and Virtual Machines

Click Next to continue and view a summary of your machine setting.

After this click Finish to initialize the machine!

When Ubuntu installation starts select “Try or Install Ubuntu”

4
Lab 1: Linux Installation and Virtual Machines

Now click on icon Install Ubuntu 24.04 LTS

5
Lab 1: Linux Installation and Virtual Machines

In the next window

 Choose your language: English and press Next Button.


 Next window is about Accessibility again press Next Button.
 In the next Window
o Select your keyboard layout: English (US)
o Select your keyboard variant: English (US)
o Press Next Button
 Next Window: Internet Connection
o Select Do not Connect to the Internet
o Press Next Button
 Next Window: Updates
o Press Skip Button
 Next Window: Type of Installation
o Select Interactive Installation
o Press Next Button
 Next Window: Applications
o Choose Default selection
o Press Next Button
 Next Window: Optimize your computer
o Uncheck both options
o Press Next Button
 Next Window: Disk Setup
o Select Erase disk and install Ubuntu
o Press Next Button
 Next Window: Create Your Account
o Your Name: Rashid Farid Chishti
o Your Computer’s Name: Chishti-PC
o User Name: chishti
o Password: rashid1234
o Confirm Password: rashid1234
o Require my password to login: Checked
o Use Active Directory: Unchecked
 Next Window: Select Your Time Zone
o Location: Karachi (Sindh, Pakistan)
o Time Zone: Asia / Karachi
o Press Next Button

6
Lab 1: Linux Installation and Virtual Machines

 Next Window: Ready to Install


o Press Install Button

7
Lab 1: Linux Installation and Virtual Machines

Linux Basic Commands


File and Directory Commands
cmd Description Examples
ls List files and directories. ls, ll, ls –al, man ls
man Take help about a command Man ls, man man
man 1 printf, man 3 printf

8
Lab 1: Linux Installation and Virtual Machines

cd change directory command cd, cd .., cd folder


pwd Print working directory pwd
cp Copy files or directories. man cp, cp file1 fl2, cp –rv folder1
fld2
mv Move or rename files and man mv, mv file1 file2, mv
directories. folder1 folder2
rm Remove/delete files or rm file, rm –r dir, rm –f file,
directories. rm –rfv dir, rmdir folder_name
mkd Create a new directory mkdir folder\ name
ir
touc Create an empty file or touch file_name,
h update modification times of touch folder_name
a file.
clea clear screen like cls clear
r command in windows

Lab Tasks
Q 1. How would you list all files, including hidden files, in a directory using the ls command?

Q 2. Which option in the ls command will display detailed information about files, such as
permissions, owner, size, and modification date?

Q 3. How do you search for a specific keyword within a manual page after opening it with the
man command?

Q 4. How would you change to the home directory using the cd command?

Q 5. How would you copy a file named file1.txt to a directory called backup using the cp
command?

Q 6. How can you copy an entire directory and its contents using the cp command?

Q 7. How can you remove a directory and all its contents recursively using the rm command?

Q 8. How would you create a directory named My Projects using the mkdir command?

9
Lab 2: Linux Basic Commands (Part 1)

Lab 2: Linux Basic Commands (Part 1)


Objective: Familiarize yourself with basic Linux commands
for file management and system navigation.

File View Commands


Comman Description Examples
d
cat Displays the entire content of a file. cat myfile.txt

More Displays the content of a file one screen more myfile.txt


at a time. You can navigate using the
spacebar.
Less Similar to more, but allows both forward less myfile.txt
and backward navigation through the
file.
head Displays the first few lines of a file. By head –n 10
default, it shows the first 10 lines. myfile.txt

tail Displays the last few lines of a file. By tail –n 20


default, it shows the last 10 lines. myfile.txt

I/O Redirection
Command Description
Example
ls -al | more the '|' tells the shell to redirects the output of the
ls -al | sort command on the left as input to the command on
the right, instead of the standard output i.e. in this
case the output of the 'ls -al' command is
redirected as input to the ‘more’ or ‘sort’
command.
ls -al > dir.out redirects the ouput of 'ls -al' into file 'dir.out',
instead of the standard output (the terminal
screen)
ls -al >> dir.out The '>>' when used instead of '>' APPENDS the
data to a file, whereas the former overwrites a file
if one already exists...or creates a new one if one
does not exist!
cat file1 file2 file3 To concatenate several files
> files
cat >> notes To add text to the end of a file
Get milk on the
way home
Ctrl-D
who | wc -l See how many users are login
wc -l < here the '<' tells the shell to make the contents of
numbers.1.0 the file numbers.1.0 as the input for 'wc'!

10
Lab 2: Linux Basic Commands (Part 1)

File Editing Commands


Comman Description Examples
d
nano A simple and user-friendly text editor. nano
myfile.txt
micro A modern terminal based text editor. more
myfile.txt
vim A powerful and versatile text editor with vi file_name
modes for navigation and editing.
emacs Another powerful text editor with extensive emacs
features. filename
gedit (GNOME Text Editor): A graphical text editor gedit
for systems using the GNOME desktop myfile.txt
environment.

Create a file using nano text editor


> nano hello.cpp
Write Following Code inside it
#include <iostream>
using namespace std;
int main (){
cout << "Hello World" << endl;
return 0;
}
Press Ctrl + X to save and Exit
Now compile program using command
g++ hello.c
On successful compilation it will create a.out file. To run this file write this command
> ./a.out

File Information Commands


Comman Description Examples
d
df Displays information about disk df –h
space usage on mounted file
systems.
du Shows the disk usage of files and du –h file_name
directories.
fdisk Displays information about disk sudo fdisk –l,
partitions on a system. sudo fdisk /dev/sdb
mount Displays information about mount | grep sda,
currently mounted file systems. sudo mount
/dev/cdrom /cdrom
pwd Prints the current working pwd
directory.

11
Lab 2: Linux Basic Commands (Part 1)

Lab Tasks
Search and view Vim tutorial on YouTube.

Q 1. Write cat command to concatenate two files file1, file2 into a new file file3

Q 2. Write a cat command to display line numbers for a file

Q 3. Write a cat command to append the contents of one file file1 to another file file2?

Q 4. How can you search for a string of text while viewing a file with the less command?

Q 5. Write a command to display first 2 lines of a file file1

Q 6. Write a command to display last 5 lines of a file file1

Q 7. Write a command to display last 4 bytes of a file file1

Q 8. Write a command to check total disk usage of /home directory in human readable format

Q 9. How can you view the partition table of a disk using the fdisk command?

Q 10. Write a command to mount an iso file to a /cdrom directory

12
Lab 3: Linux Basic Commands (Part 2)

Lab 3: Linux Basic Commands (Part 2)


Objective: Continue exploring essential Linux commands
with a focus on process management and file permissions.

System Information Commands


Comman Description Examples
d
uname Displays system information such as uname –a
kernel name, network node
hostname, kernel release, kernel
version, and machine hardware.
hostname Shows or sets the name of the hostname
current host.
Ifconfig Find IP address of the system ifconfig
uptime Shows how long the system has uptime
been running, as well as load
averages.
free Displays information about system free -h
memory usage.
lscpu Displays information about the CPU lscpu
architecture and cores.
lsusb lsusb
date Displays the current date and time. date
date +%R, date +%r, date +%D, date –d “2 days ago”
date +%d date +%d%m%h
cal Displays a calendar for the current Cal
month. cal –j
cal –y | less
w Shows who is logged in and what w
they are doing.

Process Management Commands


Command Description Examples
ps Shows information about currently ps aux
running processes.
top Gives a dynamic view of system Top
processes and resource usage.
pstree Displays a tree diagram of processes. pstree -p | less
kill Sends a signal to terminate a kill -9 1234
process. The -9 option forcefully kills
the process

killall Sends a signal to terminate all killall -9 firefox


processes with the specified name.
command_n Runs a command in background. sleep 10 &
ame & Example: (sleep 5; echo "Done") &

13
Lab 3: Linux Basic Commands (Part 2)

job Displays the status of jobs running in Job


the background.
bg Puts a job in the background. Bg
fg Brings a job to the foreground. Fg
nice Runs a command with a specified nice -n 10
priority. my_process
renice Changes the priority of an already renice +5 1234
running process.
find The find command searches for files find
/path/to/directory
in real-time. -type f -size +1M
find /path/to/directory -name
"filename"
To search in the current directory: find . -name "file*"
Example 2: find /path/to/directory -name "filename"
for case-insensitive, use -iname: find /path/to/directory -iname "filename"
wall this is msg to all Send msg to all Linux user
mesg n Block messages
mesg y Enable lock broadcast messages
write user_name your_message Ctrl+C Send msg to a specific user

Lab Tasks
Q 1. Which option of the uname command shows the kernel version?

Q 2. Which file stores the permanent hostname in most Linux distributions?

Q 3. Write date command and display date in the following format: Monday, September 9, 2024
02:42:07 PM

Q 4. Write date command and display date in the following format: 2024-09-09 14:42:07

Q 5. How can you display a calendar for October 2024 using the cal command?

Q 6. How do you sort processes by memory usage in the top command?

Q 7. How can you display the process tree with process IDs using pstree?

Q 8. How would you terminate a process with PID 1234 using the kill command?

Q 9. How would you run the sleep 60 command in the background?

14
Lab 3: Linux Basic Commands (Part 2)

Q 10. How do you start a command with a nice value of 10?

Q 11. How do you search for files larger than 100MB using the find command?

Q 12. How do you search for a directory named shared documents owned by user chishti ?

15
Lab 4: Regular Expressions

Lab 4: Regular Expressions


Objective: Understand and apply regular expressions to
search for patterns in text files.
Regular expressions (regex) in Linux are patterns used to match character combinations in
strings. They are commonly used in various Linux tools like grep, sed, awk, and vim for text
search and manipulation.
The grep command searches for patterns in files or output using regular expressions.
sed (stream editor) is used to find and replace patterns in text.
awk is a text-processing tool for extracting and manipulating data from structured text files
(like CSVs, logs, etc.). It also supports regex.
vim is a powerful text editor.

Here’s an overview of the types and components of regular expressions in the Linux console:
Common Regular Expression Components
1. Literal Characters
Matches exact characters in the string (e.g., abc matches "abc").
echo "Linux shell scripting" | grep "shell"
grep "hello" file.txt Search for a word in a file:
grep -i "hello" file.txt Case-insensitive search
echo "Hello world" | sed 's/world/Linux/'
Explanation: This replaces the first occurrence of "world" with "Linux."
2. Metacharacters
. Matches any single character except a newline.
echo "abc123" | grep "a.c" The . will match any character
grep "a.c" file.txt
^ Matches the start of a line (e.g., ^abc matches "abc" at the beginning of a line).
echo "Hello World" | grep "^Hello" matches lines starting with "Hello"
grep "^Hello" file.txt
echo -e "apple\nbanana\nelephant\ncat" | grep '^[aeiou]'
Explanation: The ^[aeiou] matches any line that begins with a vowel.
$ Matches the end of a line (e.g., abc$ matches "abc" at the end of a line).
echo "Hello World" | grep "World$" matches lines ending with "World"
grep "^...$" file.txt Match lines with exactly three characters:
\ Escapes a metacharacter, so it is treated as a literal character
The dot (.) is a metacharacter that matches any single character. To match a literal dot,
you need to escape it.
echo "file.txt" | grep "file\.txt"
Square brackets ([ ]) define a character class in regex. To match a literal opening
square bracket, it must be escaped.
echo "[test]" | grep "\[test\]"
3. Character Classes:
[abc] Matches any one of the characters inside the brackets (e.g., b or c).
echo "aAbBcC" | grep -o '[aA]'
Explanation: The class [aA] matches either lowercase a or uppercase A.
echo "This is a test" | grep -o '[aeiou]'
Explanation: The character class [aeiou] matches any vowel in the string.
Matches any character within the range specified (e.g., any lowercase letter).

16
Lab 4: Regular Expressions

[a-z] echo "123 456 789" | grep -o '[4-7]'


Explanation: The class [4-7] matches any digit between 4 and 7.
echo "Room 101, Floor 7" | grep -o '[0-9]'
Explanation: The character class [0-9] matches any digit from 0 to 9.
echo "abcdefg ABCDEFG" | grep -o '[a-f]'
Explanation: The character class [a-f] matches any lowercase letter from a to f.
grep "[0-9]" file.txt Match lines containing a digit:
echo "Sample Text 123" | grep -o '[A-Z0-9]'
Explanation: The class [A-Z0-9] matches any uppercase letter or digit.
[^abc] Matches any character except those inside the brackets.
echo "123abc456" | grep -o '[^0-9]'
Explanation: The class [^0-9] matches any character that is not a digit.
echo "Hello123!" | sed 's/[^a-z]/*/g'
Output: *****ello***
Explanation: The class [^a-z] matches anything that is not a lowercase letter and
replaces it with *.
4. Quantifiers
* Matches 0 or more of the preceding element (e.g., a* matches "", "a", "aa", etc.).
echo "a ab bb abc aabc" | grep 'a*'
a* matches any number (including zero) of consecutive a characters.
echo "fo foa fo foobar" | grep 'foo*'
The pattern foo* matches "fo" followed by zero or more os.
+ Matches 1 or more of the preceding element (e.g., a+ matches "a", "aa", etc.).
echo "hello" | grep -E 'l+o'
This matches hello because l+ means one or more l characters before o.
grep "[0-9]\+" file.txt
Match lines with one or more digits
echo "a1 123 abc 4567" | grep -E '[0-9]+'
Explanation: [0-9]+ matches one or more digits.
echo "aa a aaa ab" | grep -o 'a+'
Explanation: a+ matches one or more occurrences of the letter a.
? Matches 0 or 1 of the preceding element (e.g., a? matches "" or "a").
echo -e "color\ncolour" | grep -E 'colou?r'
This matches both color and colour because u? means u can appear zero or one
time.
{n} Matches exactly n occurrences of the preceding element (e.g., a{3} matches
"aaa").
echo "abcccccd" | grep –E "c{4}"
{n,} Matches n or more occurrences (e.g., a{2,} matches "aa", "aaa", etc.).
echo "a aa aaa aaaa" | grep -E 'a{2,}'
matches two or more occurrences of letter a.
echo "banana apple aardvark" | grep -E 'p{2,}'
The pattern p{2,} matches any occurrence of 2 or more consecutive ps.
{n,m} Matches between n and m occurrences.
echo "123 45 6789 0" | grep -E '[0-9]{3,4}'
[0-9]{3,4} matches sequences of digits that are at least 3 and at most 4 digits
long.
echo "b bb bbb bbbb" | grep -E 'b{2,3}'
Explanation: b{2,3} matches any sequence of 2 or 3 b characters.
5. Anchors
^ As mentioned earlier, anchors the pattern to the beginning of a line.

17
Lab 4: Regular Expressions

$ Anchors the pattern to the end of a line.


\b Matches a word boundary (e.g., \bword\b matches the word "word" exactly).
echo "hello world, hello there" | grep -o "\bhello\b"
This command matches the whole word hello, ensuring that "hello" is not part of
a larger word (like "helloworld").
echo "hello world" | grep "\bhello"
This matches hello only if it appears at the beginning of a word, ensuring there is
a boundary before the word.
echo "goodbye world" | grep "world\b"
This matches world only if it appears at the endof a word, ensuring no characters
follow it.
6. Grouping and Alternation
() Groups expressions (e.g., (abc) treats abc as a single unit).
echo "Current directory: $(pwd)"
# Prints the current directory
(sleep 5; echo "Completed after 5 seconds") &

I Alternation (e.g., a|b matches either "a" or "b").


echo -e "banana apples orange" | grep -E "apple|orange"
Match lines containing either of two patterns

Sed Examples
echo "Hello world" | sed 's/world/Linux/'
Output: Hello Linux
Explanation: This replaces the first occurrence of "world" with "Linux."
echo "Hello world, world" | sed 's/world/Linux/g'
Output: Hello Linux, Linux
Explanation: The g flag makes it replace all occurrences of "world" with "Linux."
echo "Phone: 555-1234" | sed 's/[0-9]/#/g'
Explanation: The character class [0-9] matches any digit and replaces it with #.
echo "This is a test" | sed 's/[aeiou]/_/g'
Explanation: The character class [aeiou] matches any vowel and replaces it with an underscore
(_).
echo "This is a test" | sed 's/ */ /g'
Output: This is a test
Explanation: * (two spaces followed by *) matches two or more spaces, and replaces them
with a single space.

Lab Tasks
Q 1. Match lines that contain exactly three digits:

Q 2. Match lines where the word "cat" is at the beginning or end of a line:

Q 3. Match lines with a specific character repeated multiple times:

Q 4. Match lines that do not contain any digits

Q 5. Match lines where the first and last characters are the same:

18
Lab 4: Regular Expressions

Q 6. Match lines containing a date in the format YYYY-MM-DD

Q 7. Match lines with a timestamp in the format HH:MM:SS

Q 8. Match lines with an IP address:

Q 9. Match lines containing a valid email address format:

Q 10. Match lines with a phone number in the format (123) 456-7890:

19
Lab 5: User Management Commands

Lab 5: User Management Commands


Objective: Learn how to manage users and groups in a Linux
environment.

User Management Commands


Command Description Examples
last Shows a list of last logins Last | grep student
sudo Executes a command with sudo command_name
superuser privileges.
su Switches to another user. sudo su – student
su - student doesn’t need student’s
it need student’s password
passwd sudo su - switch to
root
useradd Creates a user sudo useradd -m -s
/bin/bash -c "Rashid Farid
Chishti" chishti
userdel Delete a user account and sudo userdel -r chishti
related files
passwd Changes password of a sudo passwd chishti
user
whoami print effective userid Whoami

W shows who is logged in and W


what they are doing
chage Modifies password expiry sudo chage -E -1 username
details for a user. Password never expires
sudo chage -l username sudo passwd -n 9999 user
show password expiry date user cannot change
password
finger displays information about finger Chishti
the user
groupadd Creates a new group. sudo groupadd Teachers
groupdel Deletes a group sudo groupdel Teachers
groups Shows groups a user groups username
belongs to
usermod Modify a user account. sudo usermod -aG Teachers
Chishti
Id Shows user id and group id id Chishti
chown Change ownership sudo chown -r
newowner:newgroup
directory
chmod Change file permissions chmod 654 filename,
chmod -R 755
directory_name

Numeric Mode Permissions

20
Lab 5: User Management Commands

Numeric Value Permission Numeric Values Permissions


4 Read (rw- r-x
654
r--)
2 Write (rw- rw-
664
r--)
1 Execute (rwx r-x r-
755
x)

File Permissions
read We can read and copy a file but cannot modify or execute
write We can modify that file
execute We can execute but can’t read or modify

Directory Permissions
read Allows the user to view the contents of the directory (i.e., list the files and
subdirectories within it). E.g. > ls directory_name
write Allows the user to create, delete, or rename files or subdirectories within the
directory. e.g. touch directory_name/newfile.txt rm directory_name/file.txt
execute We can enter the directory using the cd command. e.g. cd directory_name
Without execute permission, even if a user has read (r) permission, they won’t be
able to traverse into the directory or open files within it.

Note: There are 3 other types of permissions too which are


Sticky Bit (t), Set Group ID bit (s), Set User ID (s)

Now make folder with your account name: mkdir > /tmp/"Your Name"
Make an empty file: touch /tmp/"Your Name"/"Your Name".txt
Now switch to student account: su - student
Now try to delete this file using student account: rm /tmp/"Your Name"/"Your Name".txt
Comeback to your account: exit

Now change folder permission: chmod 757 /tmp/"Your Name"


Again try to delete this file using student account: su - student
rm /tmp/"Your Name"/"Your Name".txt
Now this file will be deleted using student account

Come back to your account: exit


Again change folder permission: chmod 755 /tmp/"Your Name"
Make a file: echo "Hello World" > /tmp/"Your Name"/msg.txt
Now student account cannot modify this file.

Now allow read and write permission to all: chmod 666 /tmp/"Your Name"/msg.txt

Switch to student account: su - student


Send more data: echo "Hello Student" >> /tmp/"Your Name"/msg.txt
Come back to your account: exit
See file contents: cat /tmp/"Your Name"/msg.txt
Hello World
Hello Student

Linux Critical Files

21
Lab 5: User Management Commands

File Path Description


/etc/passwd This file stores user account information, including
username, user ID (UID), group ID (GID), home directory,
and shell. Passwords were historically stored here, but
now only a placeholder (x) is used, with actual passwords
moved to /etc/shadow.
/etc/ This file contains encrypted user passwords and
shadow additional security information such as password aging
and expiration policies. Only root and privileged users
can access this file to protect sensitive information.
/etc/group This file defines the groups on the system, including
group names, group IDs (GID), and the users belonging
to each group. It facilitates group-based permissions and
access control.

Lab Tasks
Q 1. How can you assign a default shell to a new user using useradd ?

Q 2. What option of passwd can lock a user account?

Q 3. How can you unlock a locked user account using passwd ?

Q 4. How can you force a user to change their password on the next login?

Q 5. Q4: Can you display the w output without showing the load averages?

Q 6. Q2: How can you remove a user along with their home directory using userdel ?

Q 7. How can you create a students group using groupadd ?

Q 8. How can you change a user’s login name using usermod?

Q 9. How do you change a user’s primary group using usermod?

Q 10. What option of usermod is used to move a user’s home directory?

Q 11. How do you recursively change ownership of a directory and its contents using chown?

Q 12. How can you change the owner and group of a file using chown in a single command?

22
Lab 5: User Management Commands

Q 13. How do you give the owner of a file read, write, and execute permissions using chmod?

Q 14. How can you remove execute permission for the group and others using chmod?

Q 15. How can you recursively change permissions for all files and subdirectories within a
directory using chmod?

23
Lab 6: Introduction to Shell Programming

Lab 6: Introduction to Shell Programming


Objective: Learn about variables, input, and output in shell
scripts.

What is Shell Scripting?

Shell scripting refers to writing a series of commands in a file and executing them as a script in the
Linux Bash shell. This allows for automation of tasks, simplifying complex workflows, and improving
productivity by running multiple commands together.

Why Use Shell Scripts?


 Automate repetitive tasks.
 Simplify complex command sequences.
 Schedule jobs using cron.
 Powerful and cost-effective solution for automation.

Creating and Running a Bash Script


To create a Bash Script File, use any text editor, like nano, vim, or gedit.
Create a script called first.sh
vi first.sh
#!/bin/bash first.sh
echo "Hello, World!"

Add the Shebang Line: The first line in a Bash script should be the shebang (#!) followed by the path
to the Bash interpreter. This tells the system which shell to use to interpret the script.

Add Commands: Add any series of Linux commands. For example:


echo "Hello, World!"

Make the Script Executable: Before running a script, you need to make it executable:
chmod +x first.sh

Run the Script: Run the script using: bash first.sh or ./first.sh

Variables: You can define and use variables without spaces. It is recommended to use capital
letters while defining a veriable.

#!/bin/bash show_name.sh
# Script to show name and age
name="Rashid Farid Chishti" # Note no spaces around =
age=46 # Note no spaces around =
echo "My name is $name and I am $age years old."

24
Lab 6: Introduction to Shell Programming

Comments: Comments start with # and are ignored by the shell:


#!/bin/bash show_system_info.sh
TIME="The current date and time: \c" # Note no spaces around =
USERS="The number of users : \c" # Note no spaces around =
PERSONAL="Account Information : " # Note no spaces around =
echo -e $TIME # use -e to enable interpretation of backslash
escapes
date # Show Current Date and Time
echo -e $USERS
who | wc -l # Show Number of Users logged in
echo $PERSONAL
finger | grep $USER # Show Your Account Information
exit 0 # Terminate script gracefully

$USER is an environment variable that contains the name of the currently logged-in user.
$HOME holds the path to the current user’s home directory.
$PATH lists directories separated by colons (:) where the system searches for executable files when
you run a command. Try this command echo $PATH in shell

Input and Output: Get input from the user with read:
#!/bin/bash get_name.sh
QUESTION="What is your name: \c"
echo -e $QUESTION
read NAME
echo "Assalam O Alikum $NAME"

Input and Output: Get user name and age:


#!/bin/bash get_info.sh
echo "Enter your name: "; read name
echo -e "Enter your age: \c"; read age
echo "Hello $name"
echo "You are $age years old"

Arithmetic Operations:
#!/bin/bash sum.sh
A=13 # In shell scripting there should be no spaces
B=8 # around the assignment operator

SUM=$(($A + $B))
echo "sum = $SUM"

25
Lab 6: Introduction to Shell Programming

#!/bin/bash expr.sh
a=10; b=5; c=2

result=$(( (a + b) * c / b )) # Combined arithmetic operation


echo "Result: $result"

Addition, Subtraction, Multiplication, Division and Remainder:


#!/bin/bash arithmetic.sh
echo -e "Enter 1st Number: \c"; read A
echo -e "Enter 2nd Number: \c"; read B

SUM=$(expr $A + $B) # Addition


DIFF=$(expr $A - $B) # Subtraction
# Multiplication (requires escaping the '*' symbol)
PROD=$(expr $A \* $B)
QUOT=$(expr $A / $B) # Division
REM=$(expr $A % $B) # Modulus (remainder)

echo "$A + $B = $SUM"


echo "$A - $B = $DIFF"
echo "$A * $B = $PROD"
echo "Quotient: $QUOT"
echo "Remainder: $REM"

Using bc (Basic Calculator): bc is a powerful command-line calculator that can handle floating-point
arithmetic.
#!/bin/bash bc1.sh
a=10.5
b=3.2

sum=$(echo "$a + $b" | bc) # Addition


diff=$(echo "$a - $b" | bc) # Subtraction
prod=$(echo "$a * $b" | bc) # Multiplication
quot=$(echo "$a / $b" | bc) # Division

echo "Sum: $sum"


echo "Difference: $diff"
echo "Product: $prod"
echo "Quotient: $quot"

Specifying Scale (Number of Decimal Places): You can use the scale parameter to specify the
precision (number of decimal places) for division or any other operations.

26
Lab 6: Introduction to Shell Programming

#!/bin/bash bc2.sh
a=10.5; b=3.2

# Division with 2 decimal places


quot=$(echo "scale=2; $a / $b" | bc)
echo -e "$a / $b = $quot"

prod=$(echo "$a * $a" | bc)


printf "$a * $b = %.2f\n" "$prod"

Using Variables in bc: You can use variables to store values and then pass them to bc for floating-
point arithmetic.

#!/bin/bash bc3.sh
a=10.7; b=4.3

# Using variables in bc for floating-point addition


result=$(echo "scale=2; x=3*$a; y=2*$b; x + y" | bc)
echo "3*$a + 2*$b : $result"

Lab Task 1:
Write a script that takes temperature in Fahrenheit converts it to Centigrade and Shows both
values. This will the output
Enter Temperature in Fahrenheit: 100
100 F = 37.78 C

Lab Task 2: Write a Script that


Calculates base^exponent (2.5^3)
Calculates square root of a number (square root of 25 = 5)
Calculates the sine of 1 radian
Calculates the natural logarithm of a number

27
Lab 7: Conditional Statements in Shell Programming

Lab 7: Conditional Statements in Shell


Programming
Objective: Understand and implement conditional
statements in shell scripts.

Using if Statement
#!/bin/bash get_number.sh
echo -e "Enter a number: \c"; read num

if [ $num -gt 10 ]; then


echo "The number is greater than 10"
fi

List of Comparison Operators


Operator Description Example
-eq Equal to if [ $a -eq $b ]
-ne Not equal to if [ $a -ne $b ]
-gt Greater than if [ $a -gt $b ]
-lt Less than if [ $a -lt $b ]
-ge Greater than or equal to if [ $a -ge $b ]
-le Less than or equal to if [ $a -le $b ]

Using if else Statement


get_number2.sh

#!/bin/bash
echo -e "Enter a number: \c"; read num

if [ $num -gt 10 ]; then


echo "The number is greater than 10"
else
echo "The number is 10 or less"
fi

question.sh

#!/bin/bash
echo -e "Do you want to proceed? (yes/no): \c"; read answer

if [ "$answer" == "yes" ]; then


echo "Proceeding..."
else
echo "Aborting..."
fi

28
Lab 7: Conditional Statements in Shell Programming

String Comparison Operators


Operator Description Example
= Equal to if [ "$a" = "$b" ]
!= Not equal to if [ "$a" != "$b" ]
< Less than (in lexical order) if [[ "$a" <
"$b" ]]
> Greater than (in lexical order) if [[ "$a" >
"$b" ]]
-z String is null (zero length) if [ -z "$a" ]
-n String is not null (non-zero length) if [ -n "$a" ]

Using nested if Statement


age.sh

#!/bin/bash
echo -e "Enter your age: \c"; read age

if [ $age -ge 18 ]; then


if [ $age -lt 60 ]; then
echo "You are an adult."
else
echo "You are a senior citizen."
fi
else
echo "You are a minor."
fi

Using nested if elif else Statement


marks.sh

#!/bin/bash
echo -e "Enter a marks out of 100: \c"; read num

if [ $num -gt 100 ]; then echo "Should be less than or equal to


100"
elif [ $num -ge 80 ]; then echo "Your Grade is A"
elif [ $num -ge 75 ]; then echo "Your Grade is B+"
elif [ $num -ge 70 ]; then echo "Your Grade is B"
elif [ $num -ge 65 ]; then echo "Your Grade is C+"
elif [ $num -ge 60 ]; then echo "Your Grade is C"
elif [ $num -ge 55 ]; then echo "Your Grade is D+"
elif [ $num -ge 50 ]; then echo "Your Grade is D"
elif [ $num -ge 0 ]; then echo "Your Grade is F"
else echo "Marks cannot be Negative"
fi
File Check file.sh

#!/bin/bash
echo -e "Enter file name: \c"; read name
if [ -e $name ]; then
echo "$name exists"
else
echo "$name does not exist"
fi

29
Lab 7: Conditional Statements in Shell Programming

Directory Check folder.sh

#!/bin/bash
if [ -d "/home/Your_Login_Name" ]; then
echo "Directory exists."
else
echo "Directory does not exist."
fi

File Comparison Operators: These operators are used to compare files.


Operator Description Example
-e File exists if [ -e "$file" ]
-f File is a regular file if [ -f "$file" ]
-d File is a directory if [ -d "$dir" ]
-s File is not empty if [ -s "$file" ]
-r File is readable if [ -r "$file" ]
-w File is writable if [ -w "$file" ]
-x File is executable if [ -x "$file" ]
-L File is a symbolic link if [ -L "$link" ]
-nt File is newer than another file if [ "$file1" -nt "$file2" ]
-ot File is older than another file if [ "$file1" -ot "$file2" ]

Using Logical Operators logical.sh

#!/bin/bash
echo -e "Enter a number: \c"; read num
if [ $num -ge 5 ] && [ $num -le 10 ]; then
echo "The number is between 5 and 10."
fi

if [ $num -lt 5 ] || [ $num -gt 10 ]; then


echo "The number is outside the range of 5 to 10."
else
echo "The number is within the range of 5 to 10."
fi

Logical Operators: These operators can be used to combine conditions.


Operator Description Example
&& Logical AND if [ condition1 ] && [ condition2 ]
|| Logical OR if [ condition1 ] || [ condition2 ]
! Logical NOT if [ ! condition ]

30
Lab 7: Conditional Statements in Shell Programming

Using test Command: The test command can also be used for conditional expressions.
#!/bin/bash test.sh
echo -e "Enter a number: \c"; read num
if test $num -eq 5; then
echo "The number is equal to 5."
else
echo "The number is not equal to 5."
fi

Using case Statement case1.sh

#!/bin/bash
echo -e "Enter a number between 1 and 3:"; read num

case $num in
1) echo "You entered ONE." ;;
2) echo "You entered TWO." ;;
3) echo "You entered THREE." ;;
*) echo "Invalid number!"
echo "Please enter a number between 1 and 3." ;;
esac

case2.sh

#!/bin/bash
echo -e "Enter your favorite fruit (apple, banana, mango): \c"
read fruit

case $fruit in
"apple" | "Apple") echo "Apples are great for a snack!" ;;
"banana" | "Banana") echo "Bananas are a good source of
potassium!" ;;
"mango" | "Mango") echo "Mangoes are tropical and
delicious!" ;;
*) echo "Sorry, I don't recognize that fruit." ;;

Lab Task 1:
Write a script that takes a file name from user.

This script checks to see

 if a file exists it show a message file exists


 if file exists and it has read permission it show a message “file has read permission”
 if file exists and it has write permission it show a message “file has write permission”
 if file exists and it has execute permission it show a message “file has execute permission”

Lab Task 2:
Write a script that uses date command to check hrs only.
 If hrs is less than 12 show message “Good Morning”
 If hrs is less than 18 show message “Good Afternoon”
 else show message “Good night”

31
Lab 7: Conditional Statements in Shell Programming

Lab Task 3:
Write a script that shows a menu

1. Display disk usage"

2. Show logged-in users"

3. Check system uptime"

Enter your choice (1/2/3):

If choice is 1 then run command: df –h

If choice is 2 then run command: who

If choice is 3 then run command: uptime

32
Lab 8: Loops in Shell Programming

Lab 8: Loops in Shell Programming


Objective: Implement loops to perform repetitive tasks in
shell programming.

for: Loop through a list of numbers


For1.sh

#!/bin/bash

for i in 1 2 5 7 11 13; do
echo "Number: $i"
done

for: Loop through a list of items


For2.sh

#!/bin/bash

for fruit in "Banana" "Orange" "Apple"; do


echo "Fruit: $fruit"
done

for: Loop through a range of numbers


#!/bin/bash For3.sh
for i in {1..5}; do
echo "Number: $i"
done

for: Using a C-style for loop with Arithmetic Operations


#!/bin/bash For4.sh
for ((i=1; i<=10; i++))
do
square=$((i * i))
echo "Square of $i is $square"
done

break: to Exit the loop


#!/bin/bash For5.sh
for i in {1..5}
do
if [ $i -eq 3 ]; then
break
fi
echo "Number: $i"
done

33
Lab 8: Loops in Shell Programming

Continue: Skip the current iteration


#!/bin/bash For6.sh
for i in {1..5}
do
if [ $i -eq 3 ]; then
continue
fi
echo "Number: $i"
done

Nesting Loops
#!/bin/bash For7.sh
for i in {1..3}
do
echo "Outer loop iteration: $i"
for j in {1..2}
do
echo " Inner loop iteration: $j"
done
done

for: Iterating over files in a directory.


#!/bin/bash For8.sh
for file in /home/login_name/*.sh # change it with
/home/login_name/*
do
echo "File: $file"
done

for: Looping through command output of ls command


#!/bin/bash For9.sh

for file in $(ls /home/login_name)


do
echo "File: $file"
done

for Loop: Looping Over Files Recursively using find


#!/bin/bash For10.sh
for file in $(find . -name "*.sh")
do
echo "Shell Script: $file"
done

34
Lab 8: Loops in Shell Programming

while: Basic while loop


#!/bin/bash While1.sh
counter=1
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++))
done

while: Infinite Loop


#!/bin/bash While2.sh
while true
do
echo "Infinite loop - press CTRL+C to stop"
sleep 1
done

while: Reading a file line by line While3.sh

#!/bin/bash
filename="for1.sh"
while IFS= read -r line; do
echo "Line: $line"
done < "$filename"

while: Reading a file line by line, show line number and total lines
#!/bin/bash While4.sh
count=0
filename="for2.sh"

while IFS= read -r line


do
echo "Line $count: $line"
((count++))
done < "$filename"

echo "Total lines: $count"

35
Lab 8: Loops in Shell Programming

Until: The until loop is the opposite of while; it continues executing until a condition becomes true.
Until1.sh

#!/bin/bash
counter=1
until [ $counter -gt 5 ]
do
echo "Counter: $counter"
((counter++))
done

Lab Task 1:
Make loop with Timeout Using read command, The script waits for user input for 5 seconds. If no
input is provided, it moves to the next iteration.
If the user gives input show “You Entered: input_name”
If it times out it shows message: "Timeout! No input provided."

Lab Task 2:
Write a shell script in which asks User a Number Then it shows if it is a prime number or not

Lab Task 3:
Write a shell script using a loop, which counts number of files in Directory /home/login_name.

36
Lab 9: Functions in Shell Programming

Lab 9: Functions in Shell Programming


Objective: To understand how to define and use functions in
shell scripts.

Functions allow you to reuse code blocks


#!/bin/bash greet.sh
greet() {
echo "Assalam O Alikum, $1"
}

greet "Student"
greet "Rashid Farid"

Functions with Local variables


#!/bin/bash multiply.sh
multiply() {
local result=$(( $1 * $2 ))
echo "Multiplication result: $result"
}
multiply 4 5

Functions with return value


#!/bin/bash add.sh
add() {
local sum=$(( $1 + $2 ))
return $sum
}

add 3 4
echo "The sum is $?"

Example: Recursive Function with Conditional Statements

37
Lab 9: Functions in Shell Programming

#!/bin/bash factorial.sh
factorial() { # Function to calculate factorial
recursively
local num=$1
if [ $num -le 1 ]; then
echo 1
else
local temp=$((num - 1))
local result=$(factorial $temp)
echo $((num * result))
fi
}

# Read input from user


read -p "Enter a number to calculate its factorial: " number

# Validate input
if ! [[ $number =~ ^[0-9]+$ ]]; then # if number is negative or
float
echo "Please enter a valid positive integer."
exit 1
fi

# Calculate factorial
result=$(factorial $number)

Working with Arguments: Bash scripts can accept command-line arguments.

Accessing Arguments
 $0 is the script name.
 $1, $2, etc., are the positional arguments.

#!/bin/bash argument.sh
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Total arguments are $#"
echo "All arguments are $*"
echo "My Process ID is $$"

Example with Arguments


./script.sh arg1 arg2 arg3

Loop Through All Arguments


#!/bin/bash loop.sh
for arg in "$@"; do
echo "Argument: $arg"
done

38
Lab 9: Functions in Shell Programming

Using Function Library


#!/bin/bash math_functions.sh
multiply_numbers() { # Function to multiply two numbers
echo $(($1 * $2))
}

#!/bin/bash main.sh

# Sourcing the external fil with functions


source ./math_functions.sh

# Calling the function from the sourced file


result=$(multiply_numbers 3 7)
echo "Multiplication of 3 and 7 is: $result"

rashid@pc1:~/lab09$ bash main.sh


Multiplication of 3 and 7 is: 21

Lab Task 1:
Make a recursive function fibonacci that accepts a number n and recursively calculates the Fibonacci
value for that position. Use the formula F(n) = F(n-1) + F(n-2) with base cases for n = 0 and n = 1.

Lab Task 2:
Make a Recursive Function gcd to Find the Greatest Common Divisor of two numbers. Implement
the Euclidean algorithm: gcd(a, b) = gcd(b, a % b) with the base case being when b = 0.

Lab Task 3:
Write a shell script to define a recursive function that finds all files of a specific type (e.g., .txt) in a
directory and its subdirectories. This a sample output

# Calling the function


find_files_recursive "./test_directory" ".txt"

./test_directory/file1.txt
./test_directory/subfolder/file2.txt
./test_directory/subfolder/subsubfolder/file3.txt

39
Lab 10: Arrays and Strings

Lab 10: Arrays and Strings


Objective: to explore arrays and string manipulation
techniques in bash shell

Arrays in Bash: Arrays in Bash are indexed collections of values. Unlike some other programming
languages, arrays in Bash are not typed, meaning that they can store any kind of value.

Array of Numbers.
#!/bin/bash numbers.sh

numbers=(11 22 33 44 55 66 77) # Declare an array of numbers


# Access elements by Index Number
echo "Number at Index 0 : ${numbers[0]}"
echo "Number at Index 1 : ${numbers[1]}"
echo "All Numbers are : ${numbers[@]}"

numbers[2]=88 # Modify elements


echo "After modification : ${numbers[@]}"

numbers+=(99) # add more elements


echo "After adding more : ${numbers[@]}"
echo "Now Array Size : ${#numbers[@]}"

unset 'numbers[2]' # Remove the element at index 5


echo "After deletion : ${numbers[@]}"

Adding all elements of an array


#!/bin/bash sum.sh

numbers=(10 20 30 40 50) # Declare an array of


numbers
sum=0
for num in "${numbers[@]}"; do
sum=$(( sum + num)) # Calculate sum
done

echo "Sum of numbers: $sum"

40
Lab 10: Arrays and Strings

Array of Strings
#!/bin/bash strings.sh

fruits=("apple" "banana" "cherry") # Create an array

echo "First fruit: ${fruits[0]}" # Access elements


echo "Second fruit: ${fruits[1]}"

fruits[1]="blueberry" # Modify elements


echo "Modified second fruit: ${fruits[1]}"

fruits+=("orange") # Add new element


echo "Added fruit: ${fruits[3]}"

echo "All fruits: ${fruits[@]}" # Print all elements

echo "Number of fruits: ${#fruits[@]}" # Show Array length

Looping Over an Array: This script loops through an array and prints each element.
#!/bin/bash loop.sh
colors=("red" "green" "blue" "yellow")
for color in "${colors[@]}"
do
echo "Color: $color"
done

Associative Arrays: Associative arrays allow you to map keys to values. Each key in an associative
array should be unique
#!/bin/bash associative.sh

declare -A capital_cities # -A tells that array will be


associative.

capital_cities["Pakistan"]="Islamabad"
capital_cities["France"]="Paris"
capital_cities["Japan"]="Tokyo"

# Access elements
echo "Capital of Pakistan: ${capital_cities["Pakistan"]}"
echo "Capital of France: ${capital_cities["France"]}"

# Incorrect change for demonstration


capital_cities["Pakistan"]="Karachi" # Modify element

echo "Modified capital of Pakistan: ${capital_cities["Pakistan"]}"

for country in "${!capital_cities[@]}" # Loop through associative


array
do
echo "The capital of $country is ${capital_cities[$country]}"

41
Lab 10: Arrays and Strings

Multi-dimensional
#!/bin/bash Arrays: Since Bash doesn't support true multi-dimensional arrays, we can
Array1.sh
simulate them using associative arrays.
declare -A matrix # -A option tells that array will be
associative.

# Initialize a 3x3 matrix


matrix[0,0]=1
matrix[0,1]=2
matrix[0,2]=3
matrix[1,0]=4
matrix[1,1]=5
matrix[1,2]=6
matrix[2,0]=7
matrix[2,1]=8
matrix[2,2]=9

# Print the matrix


for i in {0..2}; do
for j in {0..2}; do
echo -n "${matrix[$i,$j]} "
done
echo
done

Passing an Array to a Function


#!/bin/bash print.sh

print_array() { # Function to print array elements


local array=("$@")
echo "Array elements: ${array[@]}"
}

numbers=(100 200 300 400) # Declare an array

# Call function and pass array


print_array "${numbers[@]}"

String Manipulation in Bash: Strings in Bash can be manipulated using various built-in
commands. Common tasks include concatenation, extraction (substring), and reversing.

42
Lab 10: Arrays and Strings

String: concatenation and sub string


#!/bin/bash concatenation.sh
str1="Hello"
str2="World"
concatenated="$str1 $str2" # Concatenation:
echo $concatenated # Output: Hello World

str="HelloWorld"
# Substring extraction:
echo ${str:0:5} # Output: Hello
echo ${str:5:5} # Output: World

String Length: This script calculates the length of a string.


#!/bin/bash length.sh

str="Hello, World!"

echo "String: $str"


echo "Length of string: ${#str}"

Substring Extraction: This script extracts a substring from a given string.


#!/bin/bash substring.sh

str="Hello, World!"

# Extract substring starting from index 7, length of 5


substring=${str:7:5}

echo "Substring: $substring" # Output: World

Replacing Substrings: This script replaces a part of the string with another string.
#!/bin/bash replace.sh

str="I like apples"

# Replace 'apples' with 'bananas'


new_str=${str//apples/bananas}

echo "$new_str" # Output: I like bananas

43
Lab 10: Arrays and Strings

Splitting
basha String
#!/bin/bash
$ into an Array.
split.sh split.sh
Data Item: 2:35;37
Data Item: 2:36;38
str="2:35;37,2:36;38,2:37;37,2:38;39" # String to split
Data Item: 2:37;37
Data
# SetItem: 2:38;39
Internal Field Separator (IFS) to a comma (',').
IFS=',' read -r -a my_array <<< "$str"
# The <<< operator feeds the value of str as input to the read
command.
# The read command splits the input string using the specified IFS
# (comma) and stores each segment into an array array_data.

for item in "${my_array[@]}" # Print each array element


do
echo "Data Item: $item"
done

Lab Task 1:
Write a script to make an array of 6 numbers and find the maximum element in that array

Lab Task 2:
Write a script to removes duplicates from an array (Hint: Use Associative Array)

Lab Task 3:
Write a script to search a string from an array of Strings.

44
Lab 11: Debugging Techniques in Shell Programming

Lab 11: Debugging Techniques in Shell


Programming
Objective: Use trap to capture signals like SIGINT (Ctrl+C) and
SIGTERM.

Basic Debugging Techniques

1. Syntax Checking: Use the -n option with the shell to check the script for syntax errors without
executing it: bash -n script.sh

#!/bin/bash Script1.sh
echo "This is a test"
if [ -z "$1" ]; # Missing then keyword
echo "No argument provided"
fi

Now run the script: bash -n Script1.sh


Correct syntax error by adding then keyword like this: if [ -z "$1" ]; then
And run the script again. If there’s no output, it means the script has no syntax errors.

#!/bin/bash Script2.sh
for i in {1..5} # Missing 'do'
echo "Number $i"
done

Now run the script: bash -n Script2.sh


Correct syntax error by adding do keyword in for loop and run the script again.

#!/bin/bash Script3.sh
my_function() # Missing opening curly brace
echo "Inside my_function"
}
my_function

Now run the script: bash -n Script3.sh and correct syntax error

2. Verbose Mode (-v option): The -v option allows you to Prints each line of the script to the
terminal before executing it. After correcting errors run the script again: bash -v
Script2.sh
3. Execution Trace Mode (-x option): The -x option runs the script in trace mode, Outputs each
command with expanded arguments to show what exactly is being executed. This is helpful
for debugging the script’s logic: bash -x script1.sh hello world

45
Lab 11: Debugging Techniques in Shell Programming

4. Using echo Statement: Insert echo statements to track variables and logic:
echo "Var1 = $var"

5. Handling Errors with set Command: The set command can modify shell options to enable
debugging features. Common debugging options are:
a. set -x: Enables a mode that prints each command before executing it, useful for tracing the
logic flow of the script ( e.g. Misusing if or case statements.)
b. set -v: Shows the shell input lines as they are read, useful for seeing the code as it’s being
processed.
c. set -e: Causes the script to exit immediately if a command does not exist or there is a syntax
error ( missing semicolons, unclosed quotes, or incorrect use of parentheses.)

#!/bin/bash Set1.sh
set -x # Enable tracing
echo "This is a test"
invalid_command # This will trigger an error
set +x # Disable tracing
echo "Hello World"

#!/bin/bash Set2.sh
num1=10
result=$((num1 + num2)) # num2 is undefined
echo "The result is $result"

Debug the script using set -x and set -e to find and fix the error.

6. Using trap Command: The trap command can be used to catch and handle signals and errors in
the script. For example, you can clean up temporary files or execute commands when the script
receives certain signals.
a. trap 'echo "An error occurred!"' ERR: Executes the echo command when an
error occurs in the script.
b. trap 'cleanup_function' EXIT: Calls a cleanup function when the script exits.

Using trap with the ERR Signal


#!/bin/bash Trap1.sh
trap 'echo "An error occurred at line $LINENO"; exit 1' ERR
echo "Starting script..."

cp file_that_does_not_exist.txt /tmp # Command that will


fail
# now change above line to cp set1.sh /tmp/your_name.sh
echo "This message will not appear if an error occurs."

 trap '...' ERR: This sets up a trap that activates whenever an error occurs in the script
(any command that exits with a non-zero status).
 'echo "An error occurred at line $LINENO"; exit 1': This is the command to
be executed when an error is trapped:

46
Lab 11: Debugging Techniques in Shell Programming

Test the script by running it without creating the file, and observe the trap in action.

Using trap with the EXIT Signal


Running script...
#!/bin/bash Trap2.sh
Script execution complete.
trap 'echo
Script finished.
"Script
Cleaning
finished.
up Cleaning
resources.
up resources."' EXIT

echo "Running script..."


sleep 3
echo "Script execution complete."

This script uses trap command to print a message whenever the script finishes execution,
whether it was terminated by a signal or completed normally.

Handling Interruptions (SIGINT): Here, trap catches the SIGINT (Ctrl+C) signal, and SIGTERM

(kill -15 PID) allowing the script to gracefully stop a process and perform a cleanup action.

#!/bin/bash Trap3.sh
# Function to execute on receiving a SIGINT or SIGTERM signal
cleanup() {
echo -e "\n Signal caught! Performing cleanup before
exiting."
# Add any necessary cleanup commands here
rm -f temp.txt;
exit 1
}

# Setting up traps for SIGINT (Ctrl+C) and SIGTERM


trap cleanup SIGINT SIGTERM

echo "Script is running... Press Ctrl+C to trigger SIGINT."


echo "The Process ID (PID) of this script is: $$"
for i in {1..10}; do
echo "Step $i"; echo "Step $i" >> temp.txt
sleep 1 # Simulate a time-consuming task
done
echo "Script completed."

If the user presses Ctrl+C during the script’s execution, trap captures it and outputs a message,
then exits cleanly.

Press Ctrl+Z, then type kill -s SIGTERM PID_OF_THIS_SCRIPT and then run fg command

SIGNAL Value Description


SIGINT 2 Typically raised from the terminal by typing Ctrl+C
SIGQUIT 3 Typically raised from the terminal by typing Ctrl+\

47
Lab 11: Debugging Techniques in Shell Programming

SIGKILL 9 Typically used from the shell to forcibly terminate an errant process,
because this signal can’t be caught or ignored.
SIGTERM 15 Sent as a request for a process to finish. Used by Linux when shutting
down to request that system services stop. This is the default signal sent
from the kill command.
SIGTSTP 20 Terminal stop signal, often raised by typing Ctrl+Z

7. Using return and exit Codes: By checking the exit status of commands ($?), you can determine if
a command executed successfully. Zero indicates success, while non-zero values indicate failure.

Using exit code of cp Command


#!/bin/bash copy.sh
cp temp.txt /tmp/

if [ $? -eq 0 ]; then
echo "File copied successfully."
else
echo "Error occurred while copying the file."
fi

Lab Task 1:
Check syntax erro of this script using bash -n script.sh command and also write correct code

#!/bin/bash script.sh
echo "Starting the script..."
if [ $1 -gt 0] then
echo "Argument is greater than 0"
echo "Script complete."

Lab Task 2:
Write a script to count how many times SIGINT is received. The script should only terminate after
receiving SIGINT three times.

Lab Task 3:
Create a script that traps both SIGINT and SIGTERM. On receiving SIGINT, it should print "Interrupt
received!" and continue running. On receiving SIGTERM, it should print "Termination signal received.
Exiting..." and exit.

48
Lab 12: Scheduling Bash Scripts with cron

Lab 12: Scheduling Bash Scripts with cron


Objective: To understand how to automate tasks by
scheduling Bash scripts using cron

Understanding the Structure of a cron Job: The basic syntax of a cron job is
* * * * * /path/to/command

Where fields represent minute, hour, day of the month, month, day of the week, and command to
execute.
# Example of job definition:

.---------------- minute (0-59), * means every minute


| .------------- hour (0-23)
| | .---------- day of month (1-31)
| | | .------- month (1-12) OR jan,feb,mar,apr ...
| | | | .---- day of week (0-6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * command to be executed
* * * * * echo “this will execute every minute”
17 * * * * /etc/cron.hourly
25 6 * * * /etc/cron.daily
47 6 * * 7 /etc/cron.weekly
52 6 1 * * /etc/cron.monthly

First make a folder named lab12: mkdir ~/lab12


Open crontab in edit mode: crontab –e
Choose Option 1 to use vi-gtk for editing
Write a simple cron job to execute every minute and append a message to a log file:
* * * * * echo "$(date +\%r): Hello, cron!" >> ~/lab12/cron_test.log
Go to folder named lab12: cd ~/lab12
View cron_test.log after one minute: cat cron_test.log

Other Examples
0 0 * * * /path/to/script.sh # This script will run every day at midnight
0 2 * * * /path/to/script.sh # This script will run daily at 2 AM
*/15 * * * * /path/to/script.sh # This script will run after every 15 minutes
0 * * * * /path/to/hourly_task.sh # This script will run every hour
30 18 * * * /path/to/daily_task.sh # This script will run every day at 6:30 PM
0 2 * * 0 /path/to/weekly_task.sh # This script will run every Sunday at 2:30 AM
0 4 1 * * /path/to/monthly_task.sh # This script will run on 1st of every month
# at 4:00 AM
0 5 1 7 * /path/to/specific_date_task.sh # This script will run at 5:00 AM on
# July 1
0 9 * * 1-5 /path/to/weekday_script.sh # This script will run on weekdays
# (Monday to Friday) at 9:00 AM
0 9,17 * * 1-5 /path/to/reminder.sh # it will run on Weekdays at 9 AM
# and 5 PM

To Temporarily Change the Editor (For the Current Session Only): export EDITOR=vi

To Permanently Change the Editor: echo "export EDITOR=vi" >> ~/.bashrc

source ~/.bashrc

To list scheduled crontab jobs: crontab –l

49
Lab 12: Scheduling Bash Scripts with cron

Creating a Daily Backup with cron: Create a bash script named backup.sh that backs up a User’s
Home directory: vi ~/lab12/backup.sh

#!/bin/bash backup.sh
tar -czf /tmp/backup_chishti_$(date +\%F).tar.gz ~/
echo "Backup created at $(date)" >> ~/lab12/backup_log.txt

Replace Chishti with your account name


Also add execute permission: chmod +x ~/lab12/backup.sh

Schedule this script to run daily at 3:30 PM: crontab -e


30 15 * * * ~/lab12/backup.sh

View the size of backup file: ls -lh /tmp | grep backup

Using Environment Variables in cron Jobs: Create a bash script named greet.sh that that prints a
message using an environment variable. Create a new bash script: vi ~/lab12/greet.sh

#!/bin/bash greet.sh
echo "Hello, $USER! This is your scheduled message."

Also add execute permission: chmod +x backup.sh

Edit your crontab to include environment variables: crontab -e


USER=Chishti
* * * * * ~/greet.sh >> ~/lab12/greet_log.txt

Replace Chishti with your account name

To remove all cron tasks from all user accounts: sudo rm -rf /var/spool/cron/crontabs/*

Verify that the message is printed with your username in the log file: cat greet_log.txt

Lab Task 1:

Create a script monthly_backup.sh that performs a backup of your files. Schedule this script to run
on the first day of every month at 2:00 AM.

Lab Task 2:

Create a script cleanup.sh that deletes files older than 7 days in a directory. Schedule this script to
run every Sunday at midnight.

Lab Task 3:

Create a script reminder.sh that sends a reminder email. Schedule this script to run every Monday
at 9:00 AM.

50
Lab 13: Networking and Scripting

Lab 13: Networking and Scripting


Objective: To perform basic networking tasks using bash
scripts

Using Ping Command in a Bash Script


bash Ping1.sh chishti.web.app
#!/bin/bash Ping1.sh
bash Ping1.sh 8.8.8.8
# ping -c 4 sends 4 ping requests to check the network connection.
ping -c 4 "$1" # Ping the host

# Check if ping was successful


# $? checks the exit status of the ping command, 0 means
successful.
if [ $? -eq 0 ]; then
echo "$1 is reachable."
else
echo "$1 is not reachable."
fi

Script
> to Monitor
#!/bin/bash
bash Network Connectivity and Notify User on Network Failure
Ping2.sh Ping2.sh
> bash Ping2.sh chishti.web.app
host="1.1.1.1" # default host to ping
if [ $# -gt 0 ]; then # if number of arguments are greater than 0
host=$1
fi
echo "Using host: $host"

while true; do # Loop continuously check connectivity


# Ping the host and check for connectivity
ping -c 1 "$host" > /dev/null
if [ $? -eq 0 ]; then
echo "$(date): Network is up."
else
echo "$(date): Network is down!"
fi
sleep 5 # Wait for 5 seconds before checking again
done

# ping -c 1 checks network connectivity with 1 packet.


# sleep 5 waits 5 seconds between each check.

51
Lab 13: Networking and Scripting

Downloading a file from a URL using wget.


#!/bin/bash download.sh

# URL to download file from


file_url="https://chishti.web.app/sw/putty.exe"

# Download the file.


# The -O option specifies the name for the downloaded file.
wget $file_url -O putty.exe

# Check if download was successful


if [ $? -eq 0 ]; then
echo "File downloaded successfully."
else
echo "File download failed."
fi

Upload a file to an FTP server: First make a directory: /home/student/upload


#!/bin/bash ftp_upload.sh

# define FTP details


ftp_server="127.0.0.1"
ftp_user="student"
ftp_password="iiui"
local_file="chishti.exe"
remote_path="upload"

# automate FTP file upload


ftp -inv "$ftp_server" << EOF
user "$ftp_user" "$ftp_password"
cd "$remote_path"
bin
put "$local_file"
bye
EOF

# Check if the file was uploaded successfully


if [ $? -eq 0 ]; then
echo "File uploaded successfully via FTP."
else
echo "FTP file upload failed."
fi

# ftp -inv automates an FTP connection,


## where i turns off interactive prompting,
## n avoids auto-login,
## and v enables verbose output.

# The <<EOF here-doc defines an FTP session


# with commands like cd, put, and bye.

52
Lab 13: Networking and Scripting

Download a file from an FTP server: First make a directory: $HOME/download


#!/bin/bash ftp_download.sh
# Automate file download from FTP server
ftp_server="127.0.0.1"
ftp_user="student"
ftp_pass="iiui"
remote_file="chishti.exe"
remote_dir="upload"
local_dir="download"

ftp -inv $ftp_server <<EOF


user $ftp_user $ftp_pass
lcd $local_dir
cd $remote_dir
get $remote_file
bye
EOF

if [ $? -eq 0 ]; then
echo "File downloaded successfully."
else
echo "FTP download failed."
fi

Lab Task 1:

Write a shell script to download a pdf file from google drive using wget

Lab Task 2:

Write a bash script to check if a port is open on a remote server using nc (Netcat) command.

Lab Task 3:

Create a bash script to display the default gateway using the route command.

53
Lab 14: Introduction to g++ and using fork system call

Lab 14: Introduction to g++ and using fork


system call
Objective:

 Learn how to use the GNU Compiler Collection (g++) for compiling C++ programs.
 Understand process creation using the fork() system call in C.

Using the system function: You can cause a program to run from inside another program
and thereby create a new process by using the system library function.

#include <stdlib.h>

int system (const char *string);

 The system function runs the command passed to it as a string and waits for it to
complete.
 system returns 127 if a shell can’t be started to run the command and -1 if another
error occurs. Otherwise, system returns the exit code of the command.

Make a following cpp file: vi fact.cpp

54
Lab 14: Introduction to g++ and using fork system call

#include <iostream> fact.cpp


using namespace std;

int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

int main(int argc, char * argv[]) {

if (argc !=2){
cout << "Usege: " << argv[0] <<" Number \n";
exit(-1);
}

int number = atoi(argv[1]);

if (number < 0) {
cout << "Factorial of a negative number does not exist." <<
endl;
exit(-2);
}

int answer = factorial(number);


cout << answer << endl;
return 0;

Now compile the code using: g++ -o fact fact.cpp


This will generate a binary file fact
Now execute this file using: ./fact 5

This will give an answer 120


Now make another file: vi test.cpp

#include <iostream> test.cpp


#include <string.h>
using namespace std;

int main() {
int n;
cout << "Enter a Number: "; cin >> n;
string command = "./fact ";
string argument = std::to_string(n);
command += argument;
int r = system(command.data());
cout << "Returned Value = "<< r << endl;
return 0;
}

55
Lab 14: Introduction to g++ and using fork system call

Now compile the code using: g++ -o test test.cpp


This will generate a binary file test
Now execute this file:

$ ./test
Enter a Number: 5
120
Returned Value = 0

Using the fork function: fork function is used to create a new process.

 This system call duplicates the current process and creates a new entry in the process table.
 The new process is almost identical to the original, executing the same code but with its own
data space, environment, and file descriptors.
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);

#include <sys/types.h> fork.cpp


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
pid_t pid;
printf("fork program starting\n");
pid = fork();
switch(pid){
case -1: perror("fork failed"); break;
case 0: printf("We are child\n"); break;
default: printf("We are parent\n"); break;
}
exit(0);
}

56
Lab 14: Introduction to g++ and using fork system call

#include <sys/types.h> fork1.cpp


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
pid_t pid; const char *message; int n;
printf("fork program starting\n");
pid = fork();
switch(pid){
case -1: perror("fork failed"); exit(1);
case 0: message = "This is the child "; n = 20; break;
default: message = "This is the parent"; n = 5; break;
}
for( ; n > 0 ; n-- ){
puts(message); printf("my pid is %d",getpid()); sleep(1);
}
exit(0);
}

57
Lab 14: Introduction to g++ and using fork system call

Waiting for a Process

#include <sys/types.h> wait.cpp


#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
pid_t pid; const char *message;
int n; int exit_code;
cout << "fork program starting\n";
pid = fork();
switch(pid){
case -1: perror("fork failed"); exit(1);
case 0: message = "This is the child"; n = 20; exit_code =
37; break;
default: message = "This is the parent"; n = 5; exit_code = 0;
break;
}
for( ; n > 0; n--)
{ puts(message); sleep(1); }
// This section of the program waits for the child process to
finish.
if (pid != 0){
int stat_val;
pid_t child_pid; // pid_t is int data type
child_pid = wait(&stat_val);
printf("Child has finished: PID = %d\n", child_pid);
if(WIFEXITED(stat_val)) // did the process exit normally?
printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
// What was the exit code of child process

else
printf("Child terminated abnormally\n");
}
exit(exit_code);
}

Tasks 1: Write a C++ program to:

1. Create a child process using fork.


2. Print the process ID (PID) of the parent and child processes using getpid() and
getppid().
3. Print different messages from the parent and child processes.

Tasks 2: Write a C++ program to:

1. Create a child process using fork.


2. The child process should execute a shell command using the system function (e.g.,
display the contents of a file using cat).
3. The parent process should wait for the child to complete using wait.

58
Lab 14: Introduction to g++ and using fork system call

Tasks 3: Write a program to:

 Create two child processes using fork.


 Assign a unique task to each child process
 (e.g., child 1 calculates the sum of an array, child 2 finds the largest number).
 Ensure the parent process waits for all child processes to complete.

59

You might also like