0% found this document useful (0 votes)
2 views36 pages

ITLSA1-22 Week 2_Chapter_16 1

The document outlines learning outcomes for shell scripting in a Linux environment, emphasizing automation of tasks using Bash scripting techniques. It covers the structure of Bash scripts, benefits of scripting, file permissions, conditional statements, and looping constructs. Additionally, it includes practical activities for writing and executing Bash scripts to reinforce the concepts learned.

Uploaded by

kgantso14
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)
2 views36 pages

ITLSA1-22 Week 2_Chapter_16 1

The document outlines learning outcomes for shell scripting in a Linux environment, emphasizing automation of tasks using Bash scripting techniques. It covers the structure of Bash scripts, benefits of scripting, file permissions, conditional statements, and looping constructs. Additionally, it includes practical activities for writing and executing Bash scripts to reinforce the concepts learned.

Uploaded by

kgantso14
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/ 36

Linux-Based

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

• Bash scripting refers to writing scripts using the


Bash (Bourne Again SHell) language to
automate tasks.

• Bash is the default shell on most Linux


distributions. Scripts are typically used for
automating repetitive tasks, system
administration, installation processes, and other
similar tasks.
Basic Bash Script
Structure

Basic Bash Script Structure

• #!/bin/bash – Shebang that tells the system to use Bash to execute the script.

• echo – A command that prints text to the terminal.


Shebang (#)
.

• 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

Bash scripting is important in Linux for several reasons, especially for


system administrators, developers, and power users.
1. Automation of Repetitive Tasks
Bash scripts let you automate tasks like:
 Backups
 File management
 Software installation and updates
 Log rotation

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

Portability Runs across Linux/Unix


environments

Efficiency Executes many tasks quickly

Automation Reduces manual effort and errors


Activity

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

A shell script is a file containing a series of executable commands. The shell


reads this file and carries out the commands as though they have been entered directly on
the command line.
The shell is somewhat unique in that it is both a powerful command line interface to the
system and a scripting language interpreter. As we will see, most of the things that can be
done on the command line can be done in scripts, and most of the things that can be done
in scripts can be done on the command line.
We have covered many shell features, but we have focused on those features most often
used directly on the command line. The shell also provides a set of features usually (but
not always) used when writing programs.
How To Write A Simple Bash Script

Creating scripts for commonly run sequences of commands can be


very helpful.
You can save the commands as a text file and then run the sequence
as a single step. The steps required for creating a script are as
follows:

1. Create a text file containing the commands.


2. Make the top line of the file a shebang (explained later).
3. Save file.
4. Make the file executable using permissions (explained later).
5. Run the command ./myScript.sh.
Below is an example of a simple script called myscript1.sh:

The above script would be executed by running


./myscript1.sh

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:

Permissions for files shown in the first column


when running ls -l
File Permissions Con’t

• 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

Else-if (elif) Statement:


The elif statement it's shorthand for "else if." It allows branching logic
beyond a simple if/else. Syntax – if…elif…else. Used to create multiple
test conditions:

if [ condition is true ]; then


do this …
Elif [ condition is true ]; then
do this instead…
fi

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

Using the “For” Loop


Like other programming languages, bash also provides a way to loop over
a set of items. For example, given a set of names, we can print “hello” for
each:
for name in jesse james jen
do
echo "Hello $name"
done
This can be useful with the expansion we looked at in the previous
section, for example:
for i in {1..100}
do
echo "Hello $i"
done
28
Looping In Bash Scripts
Using the “For” Loop
We can also do a traditional style loop with an i++ statement as you’ve
likely seen in other languages:
for ((i=1;i<=100;i++));
do
echo "Hello $i"
done
It’s also possible to make an infinite loop:
for (( ; ; ))
Using the above syntax, let's create a hello20.sh script that will print out
"Hello World" twenty times: The loop should initialise the integer variable
i to 0, then tests the condition (i < 20); if true, it then executes the line
echo "Hello World“ and increments the variable i by one, and then the
loop runs again until i is no longer less than 20. 29

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

Using the “Until” Loop


Both the for and while loops run as long as the test condition is true. On the
other hand, the until loop continues to run as long as the test condition
remains false. That's to say, it stops running as soon as the test condition is
true.
31
Looping In Bash Scripts
“Until” Loop Syntax
The general syntax of an until loop is as follows:
until [condition is true]; do
[commands]
Done
For example, let’s create a simple count.sh script that prints out the count
numbers from 1 to 5.
#!/bin/bash
count=1
until [ $count -gt 5 ]
do
echo "Count is $count"
((count++))
done
32
Activities

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

You might also like