Unit 4 Open Source Operating System (Shell Programming)
Unit 4 Open Source Operating System (Shell Programming)
Unit 4
Open Source Operating System (SHELL
PROGRAMMING)
Content of Unit 4 :
✓ Bash Shell Scripting
✓ Executing Script
✓ Working with Variables and Input
✓ Using Control Structures
✓ Handling signals, creating functions
✓ Working sed and gawk
✓ Working with web using shell script: Downloading web page, Converting Web page content
to a text file, parsing data, working cURL.
➢ Bash Shell Scripting is a method of writing and executing commands in a sequence to automate
tasks in a Linux environment.
➢ It combines the power of the Linux command-line with programming structures, making it
possible to create scripts that perform repetitive or complex tasks more efficiently.
➢ The shell is a command-line interface (CLI) that allows users to interact with the operating
system.
➢ It interprets and executes user commands, providing an interface to the system’s services and
utilities.
➢ Bash (Bourne Again Shell) is one of the most popular Unix/Linux shells used by default on
most Linux distributions.
4. Scripting for DevOps and automation: Often used in continuous integration and deployment
pipelines.
Advantages of Bash Scripting
1. Automation: Eliminates manual effort by automating repetitive tasks.
2. System Administration: Commonly used in managing files, processes, and user accounts.
3. Efficiency: Saves time and reduces errors by simplifying complex processes.
4. Integration: Works seamlessly with other tools, programming
Some Basic Bash Commands
Some commonly used Bash commands include:
• echo: Displays messages or values.
• ls: Lists files and directories.
• pwd: Prints the current working directory.
• cp, mv, rm: Commands to copy, move, and remove files.
• chmod: Changes file permissions.
Basic Structure of a Bash Script
✓ A Bash script is a text file with the extension .sh .
✓ The first line of every script should be:
#!/bin/bash
✓ This is called a shebang, which tells the system which interpreter to use (in this case, Bash).
✓ After the shebang, you can include Bash commands, variables, and logic.
Basic Script Structure
A Bash script typically includes:
1. Shebang (#!/bin/bash): The first line of the script, indicating the interpreter.
2. Commands: Instructions written sequentially to perform tasks.
3. Variables: Store values to use in the script.
4. Control flow: Conditional and looping constructs to create logic.
➢ The primary purpose of Bash scripting is to automate tasks that would otherwise need to be
executed manually in a Linux terminal.
➢ Executing Bash scripts in Linux is straightforward once the script is written and given proper
permissions.
➢ With the ability to pass arguments, schedule scripts, and use environment variables, Bash
scripting becomes a powerful tool for automating tasks and managing systems efficiently.
Steps to Execute a Bash Script in Linux
1) Step 1: Writing a Script
✓ Before executing, we need to write a Bash script
✓ Open a text editor (e.g., nano, vi, or gedit) and create new file
nano script.sh
✓ Start the script with the shebang line to indicate the interpreter
#!/bin/bash
✓ Add the commands under the shebang line as per requirement
#!/bin/bash
echo "Hello, World!"
2) Step 2: Save the Script
✓ After writing the script, save the file with a meaningful name and a .sh extension
(though it’s not mandatory to use the extension).
3) Step 3: Make the Script Executable
✓ By default, the script might not have execute permissions.
✓ To run the script, we need to change its permissions:
chmod +x script.sh
✓ This command gives the script execute permissions, allowing it to be run like a
program.
4) Step 4: Execute the Script
✓ There are many ways to execute the script. Some of most popular method are listed
below
a) Run the script using its relative or absolute path:
. /script.sh
• The ./ indicates that the script is located in the current directory.
Here, name stores the string “SSWCOE" and age stores the number 05
b) Accessing Variable Values
➢ To access or refer to a variable's value, precede the variable name with a $ symbol.
echo $variable_name
Example
echo $name
This will output: SSWCOE
➢ If we reference a variable without the $, Bash will interpret it as plain text rather than a
variable.
c) Rules for Naming Variables
➢ Variable names can include letters, numbers, and underscores.
➢ Variable names cannot start with a number.
• Correct: my_var, VAR123, user_name
• Incorrect: 123var, -myvar
➢ Variable names are case-sensitive.
• myVar and MYVAR are treated as different variables.
d) Variables can hold different types of values:
✓ Strings: "Hello, World!"
✓ Numbers: 123
✓ Command outputs: Result of a command can be stored in a variable.
Example:
greeting="Welcome to OST Class !“
count=46
today=$(date)
✓ Here greeting holds a string, count holds a number. today holds the result of the date
command.
Variable Types
1) Local Variable:
✓ Variables which are specific to the current instance of shell. They are basically used
within the shell, but not available for the program or other shells that are started from
within the current shell.
For example:
`name=SSWCOE`
✓ In this case the local variable is (name) with the value of SSWCOE . Local variables
is temporary storage of data within a shell script.
2) Environment Variable:
✓ These variables are commonly used to configure the behavior script and programs that
are run by shell. Environment variables are only created once, after which they can be
used by any user.
For example:
`export PATH=/usr/local/bin:$PATH` would add `/usr/local/bin` to the beginning of
the shell’s search path for executable programs.
3) Shell Variables:
✓ Variables that are set by shell itself and help shell to work with functions correctly.
Here some variables are Environment variable, and some are Local Variables.
For example:
• `$PWD` = Stores working directory
• `$HOME` = Stores user’s home directory
• `$SHELL` = Stores the path to the shell program that is being used.
Variable Scope
✓ Global Variables: By default, variables in Bash are global, meaning they can be
accessed throughout the script unless declared within a function.
✓ Local Variables: To restrict a variable's scope to a function, use the local keyword.
Example:
Example:
This script will prompt the user for their name and greet them based on the input.
Common read Options:
-p: Display a prompt without using echo
3) Input Redirection
✓ Input can also be fed into a script from a file or another command using input
redirection.
✓ This is useful when you have large amounts of data.
Syntax:
command < input_file
Example:
✓ Here Documents allow multiple lines of input to be fed into a command or script,
often used to feed input directly without needing a separate file.
Syntax:
Example:
Piping Input
➢ Piping input (|) passes the output of one command as the input of another. This is especially
useful in chaining commands.
Example:
Environment Variables
✓ You can use environment variables to input data into your script.
✓ Environment variables are accessible to any script or command running within the
shell.
Example:
Special Variables
✓ $?: Exit status of the last command executed (0 for success, non-zero for error).
✓ $$: Process ID of the current script.
✓ $!: Process ID of the last background job.
✓ Always validate user input to prevent errors or unexpected behavior.
✓ Use quotes around variables to prevent word splitting issues, especially when
working with filenames or strings containing spaces.
Example
Example :
Example
Example
3. Loop Structures
➢ Loops allow repetition of commands, either for a fixed number of times or based on
conditions.
a) The for Loop
➢ The for loop iterates over a list of items.
Syntax
Example
Example
Example
b) continue Statement
✓ The continue command skips the current iteration and moves to the next one.
Handling signals
➢ In Linux, Signals are the interrupts that are sent to the program to specify that an important
event has occurred.
➢ Events can vary from user requests to invalid memory access errors.
➢ Various signals, like the interrupt signal, means that the user has asked the program to perform
something which is not present in the user flow of control.
➢ There are two kinds of signals:
A) Maskable
B) Non-Maskable
A) Maskable: - Maskable Signals are the signals that the user can change or ignore.
B) Non-Maskable: - Non-Maskable Signals are the signals that the users cannot change
or ignore. Non-Maskable signals mainly occur if a user is signaled for non-recoverable
hardware errors.
➢ There are various processes in different states in the Linux computer system.
➢ All these processes belong to either the operating system or the user application.
➢ A mechanism is required for the kernel and these processes to coordinate their activities.
➢ One method to perform this, for the process, to inform others if anything vital thing occurs.
That's the reason we have signals.
➢ Basically, the signal means a one-way notification.
➢ The kernel sent the signal to the process, to one process to itself, or another process. Linux
signals trace their origin to Unix signals.
➢ In later Linux versions, real-time signals were added.
➢ Signal inter process is an easy and lightweight form of communication and is therefore
compatible with embedded systems.
What is the Typical Lifecycle of a Signal?
A signal goes through three stages:
1) Generation
2) Delivery
3) Processing
1) Generation :
➢ A signal is generated by a process via the kernel.
➢ Whichever generates the signal addresses process to a particular process.
➢ With the help of the process number, the signal is represented, and it does not contain
any additional data or arguments.
➢ So, signals are lightweight. However, we can pass the additional signal with POSIX
real-time signals.
➢ Functions and system calls that can produce signals contain kill, sigqueue, raise,
pthread_kill, kill, and tgkill.
2) Delivery
➢ We said that the signal remains pending until it is delivered.
➢ Basically, in a small amount of time signal is delivered to the process by the kernel.
➢ If the process has blocked the signal, the process will be pending until unblocked.
3) Processing
➢ When the signal is delivered, it is processed in various ways.
➢ Each signal contains a default action such as terminate the process, ignore the signal,
stop the process, continue the process.
➢ For non-default behavior, handler function might be called. Precisely which of these
happens is stated through sigaction function.
Signals List with Meaning
The below table shows the list of the signals along with their meaning:
The SIGQUIT signal is issued when the user sends the quite
3. SIGQUIT
signal (Ctrl + D).
2. Modularity: Functions help organize scripts into logical sections, each handling a specific task.
3. Simplified Maintenance: With functions, any code changes only need to be updated in one
place, making maintenance easier.
4. Error Handling: Functions allow specific sections of code to be tested and debugged
individually.
Basic Syntax for Creating Functions
➢ In shell scripting, there are two ways to define a function
Syntax 1:
Syntax 2:
#!/bin/bash
# Function with parameters
wellcome_user() {
echo "Hello, $1! You are $2 years old College ."
}
# Call the function with arguments
wellcome_user “SSWCOE" 6
✓ $1 refers to the first argument (“SSWCOE"), and $2 refers to the second
argument (6).
✓ This function prints a customized greeting based on the parameters passed.
Returning Values from Functions
➢ Shell functions don’t return values in the same way as in other programming languages, but
you can use return to send back a status code (an integer between 0 and 255), and echo to
print output that can be captured by the calling code.
#!/bin/bash
# Function to check if a number is even
is_even() {
if [ $(( $1 % 2 )) -eq 0 ]; then
return 0 # Success
else
return 1 # Failure
fi
}
# Call the function and check the return value
number=4
is_even $number
if [ $? -eq 0 ]; then
echo "$number is even."
else
echo "$number is odd."
fi
#!/bin/bash
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}
# Calculate factorial of 5
result=$(factorial 5)
echo "Factorial of 5 is: $result"
Important Points about Functions
✓ Use descriptive names for functions to clarify their purpose (e.g., calculate_area).
✓ Document the function purpose with comments, especially if it accepts parameters
or returns specific values.
✓ Use local for variables inside functions to avoid conflicts with global variables.
✓ Avoid side effects: Functions should ideally return values and not change global
variables directly.
✓ Test functions individually to ensure they perform as expected before integrating
them into the main script.
➢ SED is a powerful text stream editor. Can do insertion, deletion, search, and
replace(substitution).
➢ SED command in UNIX supports regular expression which allows it to perform complex
pattern matching.
➢ The SED (Stream Editor) is a versatile tool for text manipulation, offering commands to
search, replace, delete, and format text efficiently. Its combination of simple syntax and
powerful regular expressions makes it ideal for automating text transformations in shell scripts,
data pipelines, and system administration tasks.
Basic Syntax of sed
sed [options] 'script' file
• Options: Flags that modify sed behaviour.
• Script: The series of commands or transformations you want to apply.
• File: The input file (or files) to be processed.
Example
#!/bin/bash
# URL of the web page to download
URL="https://www.google.com"
#!/bin/bash
3) Parsing data
#!/bin/bash
WARNINGS_FILE="warnings.txt"
# Provide summary
echo "Parsing complete."
echo "Errors saved in $ERRORS_FILE."
echo "Warnings saved in $WARNINGS_FILE."
4) Working cURL.
#!/bin/bash
WEB_URL="https://www.google.com"
# Send a GET request to the API and save the response to a file
echo "Sending GET request to $API_URL..."
curl -s -o "$API_GET_RESPONSE" "$API_URL"
if [ $? -eq 0 ]; then
echo "API GET response saved to $API_GET_RESPONSE."
else
echo "Failed to fetch data from API."
fi