ITLSA1-22 Week 2_Chapter_16 1
ITLSA1-22 Week 2_Chapter_16 1
Operating Systems
ITLSA1 - B22
Learning Outcomes - Week 2
1. Explain and apply shell scripting techniques to automate simple
repetitive tasks in a Linux environment.
1.1 Write simple scripts that include loops and conditional statements for
basic automation.
1.2 Outline steps to include functions within scripts to organise code.
• 1.3 Run and check scripts to ensure correct output and identify common
errors.
Bash Scripting
• #!/bin/bash – Shebang that tells the system to use Bash to execute the script.
• A shebang refers to the first line in a script, when that line begins with #!.
• The word comes from the musical notation term for # sharp and the! sometimes
being called “bang”; combining these two becomes “sharp-bang” or shebang for
short.
• The shebang, when used as the first line of a file, specifies the program that will
be used to interpret the script.
• The most popular one relevant to writing Linux scripts is
#!/bin/bash
• The same thing can be expressed using
/usr/bin/env, which increases portability by using whatever version of bash is found
in the user’s path.
#!/usr/bin/env bash
Benefits of Bash Scripting
7
Benefits of Bash Scripting
Con’t
2. System Administration
• System admins use Bash scripts to:
• Schedule jobs via cron
• Manage user accounts and permissions
• Monitor system health (CPU, memory, disk)
• Deploy and configure servers
3. Task Efficiency
• Using a Bash script can execute multiple commands at once, making it
much faster than typing them manually.
• Example: Setting up a development environment or cleaning up logs can
be accomplished with a single script.
8
Benefits of Bash Scripting
Con’t
4. Portability
• Bash scripts are just plain text and can run on almost any Unix-like
system (Linux, macOS, etc.) without modification.
5. Integration with Other Tools
Bash scripts can interact with:
• Other programming languages (Python, Perl)
• Command-line tools (awk, sed, curl, etc.)
• System calls and APIs.
This makes Bash a powerful language for integration
6. Learning and Debugging
• Bash helps users understand how the system works "under the
hood" and allows step-by-step debugging using set -x and logging
9
Benefits of Bash Scripting
Con’t
7. Batch Processing
You can easily process files or commands in bulk, for example:
• Renaming thousands of files
• Converting file formats
• Searching logs for patterns
✅.
8. Job Scheduling
With cron and at, Bash scripts can run tasks at specific times, enabling:
• Daily database dumps
• Weekly cleanup jobs
• Monthly reports
10
Summary Table
Benefits Description
Integration Works well with other command-
line tools
Control Gives fine-grained access to system
functionality
Create a Bash script named hello.sh that performs the following tasks:
1. Prints the message: "Hello, this is my first Bash script!"
2. Save the script.
3. Make the script executable from the terminal.
4. Run the script and ensure the output displays correctly.
What Are Shell Scripts
When the script is run, the first line will output: Hello Vossies!, the second line:
My working directory is:, and the last line will display your current working
directory. See figure below:
Bash Script Output
Executable Permissions
• The step to making a script executable is to change the file's
permissions to allow execution. The short and simple way of doing
this is to run: chmod +x filename.sh
• This simply adds the execution permission to the file for our current
user. After running the command, you’ll be able to make use of it
simply by running the following (assuming you’re in the same
directory as the file): ./filename.sh
• It’s worth understanding the concept of permissions on Linux as it’s
a crucial aspect of the operating system. Every file has three
different types of permissions:
1. • Read
2. • Write
3. • Execute
File Permissions Con’t
Each of these three permissions can be set separately for the three groups:
• User
• Group
• Others
When using ls -l, you can see the set permissions for each file expressed
on the left-hand side, as shown:
• Note
The first letter in this ten-letter sequence is used to indicate special
file types. The possible values are
• d=directory
• c=character device
• s=symlink
• p=named pipe
• s=socket
• b=block device, and
• D=door.
However, we don’t have to deal with these special types, but it’s worth knowing what the first
letter is.
19
Components of a File
Permissions
After the first letter, which indicates special file types, there are nine more letters. We
can break these nine letters into three sets of three, as shown in the Figure below – the
first being file permissions for the file owner, the second for the user group, and the
third for all other users.
For the three sections, we have three
different letters which, if present,
indicate that groups have said
permission:
• r = read
• w = write
• x = execute
Conditional Statements
If Statement:
This is a conditional expression in bash with a series of possible tests, each
with its specific option. For example, if we want to check if a file exists, we’d
Use the -e option. Let’s create the following script:
21
Conditional Statements
If Statement:
When you run the script, you should get the output “passwd exists”. Try
changing /etc/passwd to a file that doesn’t exist. Or if you’d like to test if the
file doesn’t exist, you can add a ! as shown in the following:
if [ ! -e /etc/passwd ]; then
22
Conditional Statements
23
Activity
• Write a Bash script that prompts the user to enter a numerical mark (0–100),
then prints out the corresponding grade based on the following criteria:
1. 90 and above: Grade A
2. 80–89: Grade B
3. 70–79: Grade C
4. 60–69: Grade D
5. Below 60: Grade F
Use if, elif, and else statements to implement the logic.
Conditional Expression
Options
The list is quite long and can be found by running “man bash” and
scrolling down to the conditional expression section. Some of the more
commonly used flags are shown below:
25
Note:
• Use [ and ] for conditions (or [[ and ]] for more advanced expressions).
• Always close the entire if block with fi.
Comparison operators for numbers:
• -eq (equal), -ne (not equal)
• -lt (less than), -le (less or equal)
• -gt (greater than), -ge (greater or equal)
Sample Solution:
Looping In Bash Scripts
Now
Looping In Bash Scripts
Using the “For” Loop
30
Looping In Bash Scripts
Using the “While” Loop
The while loop is another popular and intuitive loop. The general syntax for
a while loop is as follows:
while [ condition is true ]; do
// do something
Done
1. Write a Bash script that continuously checks for the existence of a specific file
(e.g., /tmp/trigger.txt). The script should:
i. Display a message like "Waiting for /tmp/trigger.txt to be created...".
ii. Use an until loop to repeatedly check for the file every 2 seconds.
iii. Print "Still waiting..." during each check.
iv. Once the file exists, exit the loop and display a message: "File
/tmp/trigger.txt detected. Proceeding with the script."
Bash Script Functions
In Bash, a function allows you to group commands together and call them
by name, which helps you reuse code and organise scripts better. The
general syntax for a bash function is as follows:
function_name () {
<commands>
}
Exercise:
Write a Bash script that defines a function called greet_user. The function
should:
1. Accept a name as an argument.
2. Print a greeting message in the format:
"Hello, [Name]! Welcome to EDUVOS!"
34
Any Question?
Week 3