Lab Manual OS
Lab Manual OS
CS_301 L
Operating Systems Lab
Lab Manual
Subject Teacher:
Lab Instructor:
Prepared by:
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.
iii
Operating Systems Lab Rubrics
Name: Reg. No.: Signature: Instructor:
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
https://ubuntu.com/download/desktop
https://www.virtualbox.org/wiki/Downloads
1
Lab 1: Linux Installation and Virtual Machines
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.
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
4
Lab 1: Linux Installation and Virtual Machines
5
Lab 1: Linux Installation and Virtual Machines
6
Lab 1: Linux Installation and Virtual Machines
7
Lab 1: Linux Installation and Virtual Machines
8
Lab 1: Linux Installation and Virtual Machines
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)
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)
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 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 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?
12
Lab 3: Linux Basic Commands (Part 2)
13
Lab 3: Linux Basic Commands (Part 2)
Lab Tasks
Q 1. Which option of the uname command shows the kernel version?
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 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?
14
Lab 3: Linux Basic Commands (Part 2)
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
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
17
Lab 4: Regular Expressions
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 5. Match lines where the first and last characters are the same:
18
Lab 4: Regular Expressions
Q 10. Match lines with a phone number in the format (123) 456-7890:
19
Lab 5: User Management Commands
20
Lab 5: User Management Commands
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.
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 allow read and write permission to all: chmod 666 /tmp/"Your Name"/msg.txt
21
Lab 5: User Management Commands
Lab Tasks
Q 1. How can you assign a default shell to a new user using useradd ?
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 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
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.
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.
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
$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"
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
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
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
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
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
27
Lab 7: Conditional Statements in Shell Programming
Using if Statement
#!/bin/bash get_number.sh
echo -e "Enter a number: \c"; read num
#!/bin/bash
echo -e "Enter a number: \c"; read num
question.sh
#!/bin/bash
echo -e "Do you want to proceed? (yes/no): \c"; read answer
28
Lab 7: Conditional Statements in Shell Programming
#!/bin/bash
echo -e "Enter your age: \c"; read age
#!/bin/bash
echo -e "Enter a marks out of 100: \c"; read num
#!/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
#!/bin/bash
if [ -d "/home/Your_Login_Name" ]; then
echo "Directory exists."
else
echo "Directory does not exist."
fi
#!/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
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
#!/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.
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
32
Lab 8: Loops in Shell Programming
#!/bin/bash
for i in 1 2 5 7 11 13; do
echo "Number: $i"
done
#!/bin/bash
33
Lab 8: Loops in Shell Programming
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
34
Lab 8: Loops in Shell Programming
#!/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"
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
greet "Student"
greet "Rashid Farid"
add 3 4
echo "The sum is $?"
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
}
# 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)
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 $$"
38
Lab 9: Functions in Shell Programming
#!/bin/bash main.sh
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
./test_directory/file1.txt
./test_directory/subfolder/file2.txt
./test_directory/subfolder/subsubfolder/file3.txt
39
Lab 10: Arrays and Strings
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
40
Lab 10: Arrays and Strings
Array of Strings
#!/bin/bash strings.sh
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
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"]}"
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.
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
str="HelloWorld"
# Substring extraction:
echo ${str:0:5} # Output: Hello
echo ${str:5:5} # Output: World
str="Hello, World!"
str="Hello, World!"
Replacing Substrings: This script replaces a part of the string with another string.
#!/bin/bash replace.sh
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.
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
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
#!/bin/bash Script2.sh
for i in {1..5} # Missing 'do'
echo "Number $i"
done
#!/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.
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.
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
}
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
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.
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
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:
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
source ~/.bashrc
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
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."
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
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"
51
Lab 13: Networking and Scripting
52
Lab 13: Networking and Scripting
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
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>
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.
54
Lab 14: Introduction to g++ and using fork system call
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
if (argc !=2){
cout << "Usege: " << argv[0] <<" Number \n";
exit(-1);
}
if (number < 0) {
cout << "Factorial of a negative number does not exist." <<
endl;
exit(-2);
}
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
$ ./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);
56
Lab 14: Introduction to g++ and using fork system call
57
Lab 14: Introduction to g++ and using fork system call
else
printf("Child terminated abnormally\n");
}
exit(exit_code);
}
58
Lab 14: Introduction to g++ and using fork system call
59