0% found this document useful (0 votes)
6 views29 pages

Systems Programming Presentation

The document provides an overview of shell scripting constructs in Unix/Linux, including conditional statements, looping constructs, and case statements. It also covers interactive scripts for user input, file management, and login systems, as well as macro behavior simulation using functions and aliases. Additionally, it discusses wildcards, shell variables, and the structure of the Unix file system.

Uploaded by

francismungangu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

Systems Programming Presentation

The document provides an overview of shell scripting constructs in Unix/Linux, including conditional statements, looping constructs, and case statements. It also covers interactive scripts for user input, file management, and login systems, as well as macro behavior simulation using functions and aliases. Additionally, it discusses wildcards, shell variables, and the structure of the Unix file system.

Uploaded by

francismungangu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

SYSTEMS

PROGRAMMING
PRESENTATION
ICS: 2305
SHELL SCRIPT CONSTRUCTS
Shell scripts are a set of commands executed by the Unix/Linux 2

shell. Constructs help to control the flow, make decisions, and


interact with users.
Conditional Statements:
If Statement
#!/bin/bash
num=10
if [ $num -gt 5 ]; then
echo "Number is greater than 5"
fi
IF-ELSE STATEMENT
3
#!/bin/bash
echo "Enter a number:"
read num

if [ $num -lt 0 ]; then


echo "Negative number"
else
echo "Positive number or zero"
fi
IF-ELIF-ELSE STATEMENT
4
#!/bin/bash
echo "Enter marks:"
read marks

if [ $marks -ge 90 ]; then


echo "Grade: A"
elif [ $marks -ge 70 ]; then
echo "Grade: B"
else
echo "Grade: C"
fi
LOOPING CONSTRUCTS
5
For Loop:
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Number: $i"
done

While Loop:
#!/bin/bash
count=1
while [ $count -le 5 ]
do
echo "Counter: $count"
((count++))
done
UNTIL LOOP:
6
#!/bin/bash
n=1
until [ $n -gt 5 ]
do
echo "Until loop number: $n"
((n++))
done
CASE STATEMENT
7
#!/bin/bash
echo "Enter a character:"
read char

case $char in
[a-z]) echo "Lowercase Letter";;
[A-Z]) echo "Uppercase Letter";;
[0-9]) echo "Digit";;
*) echo "Special Character";;
esac
CASE STATEMENT
#!/bin/bash 8
case "$2"
in
"+") ans=`expr $1 + $3`
printf "%d %s %d = %d\n" $1 $2 $3 $ans
;;
"-") ans=`expr $1 - $3`
printf "%d %s %d = %d\n" $1 $2 $3 $ans
;;
"\*") ans=`expr "$1 * $3"`
printf "%d %s %d = %d\n" $1 $2 $3 $ans
;;
"/") ans=`expr $1 / $3`
printf "%d %s %d = %d\n" $1 $2 $3 $ans
;;
# Notice this: the default case is a simple *
*) printf "Don't know how to do that.\n"
;;
INTERACTIVE SHELL SCRIPT
Simple Calculator:
9
#!/bin/bash

echo "Welcome to Bash Calculator"


echo "Enter first number:"
read a
echo "Enter second number:"
read b

echo "Choose operation: + - * /"


read op

case $op in
+) result=$((a + b));;
-) result=$((a - b));;
\*) result=$((a * b));;
/)
if [ $b -ne 0 ]; then
result=$((a / b))
else
echo "Cannot divide by zero"
exit 1
fi
;;
*) echo "Invalid operator"; exit 1;;
esac
USER INFORMATION SCRIPT
• #!/bin/bash

• echo "Enter your name:"


• read name

• echo "Enter your age:"


• read age

• echo "Enter your country:"


• read country

• echo ""
• echo "=== User Information ==="
• echo "Name: $name"
• echo "Age: $age"
• echo "Country: $country"
FILE EXISTENCE CHECKER
#!/bin/bash

echo "Enter the filename to check:"


read filename

if [ -f "$filename" ]; then
echo "File exists."
else
echo "File does not exist."
fi
ADVANCED INTERACTIVE SHELL SCRIPT FOR
A MENU-DRIVEN FILE MANAGER 12

This script allows the user to perform file operations such as creating, viewing, renaming, deleting, and listing files
through an interactive menu.
• Menu-Driven File Manager (Advanced Shell Script)
• #!/bin/bash

• # Menu-Driven File Manager Script

• while true
• do
• echo ""
• echo "========= File Manager Menu ========="
• echo "1. Create a File"
• echo "2. View a File"
• echo "3. Rename a File"
• echo "4. Delete a File"
• echo "5. List All Files"
• echo "6. Exit"
• echo "====================================="
• echo -n "Choose an option [1-6]: "
• read choice


SECURE, INTERACTIVE SHELL SCRIPT FOR A USER LOGIN
AND PASSWORD CHECK SYSTEM 13
This script simulates a basic login system with:A predefined
username-password pair (stored in a file or hardcoded).Masked
password input using read -s.Login attempts limitation.

Version 2: Using Stored Credentials in a File


You can also store user credentials in a file in the format:
username:password.👇 Step 1: Create a users.txt file

# Format: username:password
admin:admin123
guest:guest321

Step 2: Script to Read from File and Validate Login


SCRIPT TO READ FROM FILE AND VALIDATE LOGIN
#!/bin/bash
CREDENTIALS_FILE="users.txt" 14
echo "=============================="
echo "🔐 Login with File Validation"
echo "=============================="
attempts=0
max_attempts=3

while [ $attempts -lt $max_attempts ]; do


echo -n "Enter Username: "
read username
echo -n "Enter Password: "
read -s password
echo ""
valid_user=$(grep -w "$username:$password" "$CREDENTIALS_FILE")

if [[ -n "$valid_user" ]]; then


echo "✅ Login successful! Welcome, $username."
exit 0
else
((attempts++))
echo "❌ Incorrect username or password. Attempt $attempts of $max_attempts."
fi
done
echo "🚫 Login failed. Exiting system."
Interactive User Login and Password Check Script
Version 1: Simple Login System (Hardcoded Credentials)
15
#!/bin/bash

# Hardcoded user credentials (for demo purposes)

USERNAME="admin"

PASSWORD="pass123"

echo "========================="

echo " 🔐 Secure Login Panel"

echo "========================="

attempts=0

max_attempts=3

while [ $attempts -lt $max_attempts ]; do

echo -n "Enter Username: "

read input_user

echo -n "Enter Password: "

read -s input_pass

echo ""

if [[ "$input_user" == "$USERNAME" && "$input_pass" == "$PASSWORD" ]]; then

echo "✅ Login successful! Welcome, $input_user."

exit 0

else

((attempts++))
MACRO LANGUAGE, MACRO-PROCESSORS, AND
MACRO INSTRUCTIONS (SHELL SCRIPTING) 16
Macro Language:
Macro language allows you to define a sequence of commands or code blocks once
and reuse them multiple times with different arguments. It's used to automate
repetitive tasks and abstract complex sequences.
In shell scripting, functions and aliasing simulate macro behavior.
Macro Processor:
Replaces macro invocations with the corresponding block of code (known as macro
expansion)
Accepts parameters for substitution. In Unix/Linux:Shell itself acts as a macro
processor using functions, aliases, and eval.
Macro Instructions:
Macro Definitions: Set of commands defined once and reused.
Macro Invocation: Calling the macro with optional arguments.
Parameter Substitution: Replace placeholders with actual values during expansion.
SIMULATING MACRO BEHAVIOR IN SHELL SCRIPTS 17
Using Functions (Simulated Macros)
Example 1: Simple Macro Using Shell Function

#!/bin/bash

# Macro definition (function)


say_hello() {
echo "Hello, $1!"
}

# Macro invocation
say_hello "Alice"
say_hello "Bob"
PARAMETERIZED MACROS
Example 2: Macro with Multiple Arguments 18
#!/bin/bash

greet_user() {
echo "Hello $1, your role is $2."
}

# Calling macro
greet_user "James" "Admin"
greet_user "Clara" "User"
USING ALIASES (VERY SIMPLE MACROS)
alias ll='ls -alF' 19

alias greet='echo "Hello, welcome!"'

Using eval for Runtime Expansion:

#!/bin/bash

macro="ls -lh"
echo "Running macro: $macro"
eval $macro
ADVANCED MACRO-LIKE USE CASE: FILE OPERATIONS
20
Example: Macro to Backup and Compress:
#!/bin/bash
backup_and_compress() {
src=$1
dest=$2
ts=$(date +"%Y%m%d_%H%M%S")
filename="backup_${ts}.tar.gz"
tar -czf "$dest/$filename" "$src"
echo "Backup of $src saved as $dest/$filename"
}
# Call macro
backup_and_compress "/home/user/Documents" "/home/user/Backups"
21
MACRO EXPANSION STEPS
Define a macro (e.g., function)
Invoke the macro (with/without parameters)
Expand: Replace the macro with actual commands
Execute: The shell runs the expanded commands

• Macro Languages automate repetitive patterns


• Macro Processors handle macro definitions and expand them
• Shell scripting uses functions, aliases, and scripts to emulate macro
behavior
• Useful for backup automation, greeting scripts, installation setups, etc.
22

• Wildcard characters in Unix/Linux allow the matching of files in an


abstracted way. Rather than having to perfectly match a file or directory’s
exact name and casing, you can insert wildcards to allow variations and
match multiple files. Using wildcards to match multiple files is known as
filename expansion, or "globbing" in some shells (like Bash).
• Asterisk (*) and question mark (?) are the two wildcard characters
• Both of these will match any character (including spaces, punctuation, and
non-UTF symbols). The asterisk matches any number of characters
(including zero), and the question mark matches exactly one character.
WILDCARDS, SHELL VARIABLES, AND SHELL SCRIPT 23

Wildcards are special characters used to represent unknown or variable characters in


file and directory names. They are often used with commands like ls, rm, cp, mv,
and more.

Wildcard Example Script:


#!/bin/bash
echo "List of all .sh files:"
ls *.sh

echo "Files starting with 't' and ending in .txt:"


ls t*.txt

echo "Files with single-character names ending in .log:"


ls ?.log
SHELL VARIABLES 24
• A Shell Variable stores data like strings or numbers, used for command execution and scripting.
Types of Shell Variables:
User-defined Created by the user name="Alice“
System-defined Provided by the shell environment $HOME, $USER

Variable Usage Example:


#!/bin/bash

# User-defined variables
name="Alice"
age=21

# System-defined variables
echo "Username: $USER"
echo "Home directory: $HOME"

# Print user variables


echo "Hello, my name is $name and I am $age years old."
25
SHELL SCRIPT CODES (EXAMPLES WITH CONCEPTS)
Script with Variables:
#!/bin/bash
user="John"
echo "Welcome, $user!"

Create Backup with Wildcards and Variables:


#!/bin/bash

src_dir="/home/student/documents"
backup_dir="/home/student/backup"
timestamp=$(date +"%Y%m%d_%H%M%S")

echo "Backing up all text files (*.txt)..."


cp "$src_dir"/*.txt "$backup_dir"/backup_$timestamp/
LOOP USING WILDCARDS 26

• #!/bin/bash

• echo "Listing all .sh files and line counts:"


• for file in *.sh
• do
• echo "$file - $(wc -l < "$file") lines"
• done
27
4. Pipes - UNIX allows you to link commands together using a pipe. The pipe acts as
a temporary file which only exists to hold data from one command until it is
read by another.
Structure of the file system
• The UNIX file system is organised as a hierarchy of directories starting from
Immediately below the root directory are several system directories that contain
• UNIX system directories
• Home directory
• Pathnames
• UNIX system directories
The standard system directories are shown below. Each one contains specific
types
of file. The details may vary between different UNIX systems, but these
directories
should be common to all. Select one for more information on it.
28
THANK
YOU
Geoffrey Sagwe
0705497178
[email protected]

You might also like