0% found this document useful (0 votes)
7 views

lecture 6

This document provides an overview of shell scripting, including its definition, elements, and basic operations. It covers the use of variables, arrays, and operators, as well as the vi editor for writing scripts. The document also includes examples of shell scripts and quizzes to test understanding of the material.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

lecture 6

This document provides an overview of shell scripting, including its definition, elements, and basic operations. It covers the use of variables, arrays, and operators, as well as the vi editor for writing scripts. The document also includes examples of shell scripts and quizzes to test understanding of the material.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Linux and shell programming

Lecture 6: Basics for Shell Programming

© spring 2025 – Dr. Dina Awny


Table of Contents

● What is shell scripting?


● Variables and Strings
● Arrays
● Basic Operators

● Shell Decision Making


What is Shell Scripting?

● We've seen how to execute commands in the shell and pipe multiple commands together.

● Sometimes, we want to run many, many commands together and/or make use of control flow
expressions such as conditionals and loops.

● That's where shell scripting comes in.


Shell Scripting

• A shell script is a text file that contains a


sequence of commands for anoperating
system.

• It is called a script because it combines a


sequence of commands—that would
otherwise have to be typed into a keyboard
one at a time—into a single script.

Page - 4
Shell Scripting

● Most shells have their own scripting language, each with its own variables, control
flow, and syntax.

● What makes shell scripting different from other scripting languages is that it is optimized
for performing shell-related tasks.

● Creating command pipelines, saving results into files, and reading from standard input are
baked into in shell scripting, making it easier to use compared to other scripting languages.

● Each shell script is saved with `.sh` file extension e.g., myscript.sh.

Page - 5
Basics of Bash Scripting
• Bash scripting refers to writing a script for a bash shell (Bourne Again Shell).
• Youcan check what shell you are using byrunning

• A shell script comprises the following elements –


- Shell Keywords – if, else, break etc.
- Shell commands – cd, ls, echo, pwd, touch etc.
- Functions
- Control flow – if..then..else, case and shell loops etc.
Page - 6
Vi editor

• To write this script, first we will introduce the vi (pronounced “vee eye”) text editor, one of the core
programs in the Unix tradition.
• The vi editor is an ASCII text editor available on every Linux distribution.
• The vi editor can be executed both in a CLI interface and a GUI interface
• While new features have been added to the vi editor, the core functions have been around for
decades
• vim (vi improved) has additional features
• To open the vi editor, you simply need to type vi followed by the filename in your terminal. For
example: vi script.txt

Page - 7
Modes of vi
● Three modes in vi:
• Command mode is used to position the
cursor within the file and edit text
• Insert mode is used to type text
• Exec or last-line (named because
commands are entered on the last line of
the screen) mode is used save the file, quit
vi, perform searches, and set editor
preferences
Page - 8
Command Mode: Cursor-positioning Commands
• Press the Esc key to enter Command mode

vi key vim key Movement


h ← Left one character
j ↓ Down one line
k ↑ Up one line
l → Right one character
w One word forward
b One word back
^ Beginning of line
$ End of the line
G Goes to the last line
Page - 9
ex mode Commands
● Type “:” to enter ex mode from command mode

Ex command Purpose
:w Write the current file to the filesystem
:w filename Save a copy of the current file as filename
:w! Force writing to the current file
:1 Go to line number 1 or whatever number is given
:e filename Open filename
:q Quit if no changes made to file
:q! Quit without saving changes to file
:set nu Display line numbers
:set showmode Displays current mode of operation
Page - 10
/ string, ?string Searches forward (/) or backward (?) through file for string
Important Editors
1. gedit Editor

2. nano Editor

Page - 11
Your F i r s t S c r i p t

Here is a super simple bash script called hello.sh:

#!/usr/bin/env bash

echo "Hello world!"

The shebang is the very


first line of a script

• The shebang is used to specify the interpreter that the given script will berunwith.In ourcase, we indicate that
we want a bash interpreter (i.e. abash shell).

Page - 12
Shebang

• A note about shebangs:

• There are a number of different ways to write your shebang such as

#!/usr/bin/env bash and #!/bin/bash

• We recommend that you always use the former as it increases the portability of your script.
• The bash command whereverit lives in the system, as opposed to just looking inside of /bin

• Youcan always run a shell script bysimply prepending it with a shell interpreter program:

Page - 13
Running (Your V e r y F i r s t Script)

Youcan always run a shell script bysimply prepending it with a shell interpreter program

sh hello.sh bash hello.sh zsh hello.sh

Interpreter

Page - 14
Running (Your Very First Script)

• You can also run a script by turning it into an executable program and then running it.

First, turn the program into an executable using chmod (change mode):

chmod +x hello.sh

Makes the program executable

Then run the program:


./hello.sh

Page - 15
Variables and Data Types
● Variables in Linux shells are like little containers that hold information for us.
● Rules for Naming Variables:
1. Start with a letter (a-z, A-Z) or underscore (_).
2. Can contain letters, numbers, and underscores.
3. Are case-sensitive (myVar is different from MyVar).
4. No spaces or special characters allowed.
● To define variables use the assignment operator (=).
The basic syntax: variable_name=value

Important note: There should be no spaces around the '=' sign.


If your value contains spaces, enclose it in quotes.
Page - 16
Accessing Values
● To access the value of a variable, we use the dollar sign ($) followed by the variable name.

Page - 17
Read-only Variables

● To create variables that can't be changed once set.


● These are called read-only variables.
● To create a read-only variable, use
the readonly command:
Unsetting Variables
● To remove a variable entirely, use the unset command.
● Once a variable is set as read-only, its value cannot be
changed or unset for the duration of the shell session.

Page - 18
Variable Types
1. Types of Variables in Shell Scripting:
•Scalar variables: Hold single values (e.g., name="John").
•Arrays: Hold multiple values indexed numerically (e.g.,
colors=(red green blue)).
•Shell scripting doesn't have explicit data types (like int, float, or
string) as seen in other languages. All variables are essentially
strings.
2. Arrays in Shell Scripting:
•Arrays allow you to store and access multiple values using indices.
•To access a specific element, use curly braces {} and the index,
like array[0].

Page - 19
Special Variables

● special variables are predefined variables that the shell uses to convey
information about the current shell environment, scripts, and commands
such as positional parameters $0, $1 ….
● These variables are often used in scripting and command-line operations
to control behavior or retrieve specific information.

Page - 20
Types of Special Variables
1. Positional Parameters
•Represent arguments passed to a script or function.
•Examples:
•$0: The name of the script or function.
•$1, $2, ..., $n: The first, second, ..., nth argument. ./ file_name arg1 arg2 to run script
•$#: The total number of arguments passed.
•"$*": All arguments as a single string.
•"$@": All arguments as separate strings.

Page - 21
2. Exit Status and Process Control
•$?: The exit status of the last command or script.
•0 indicates success; any other value indicates failure.
•$$: The Process ID (PID) of the current shell.
•$!: The PID of the last background command.
3. Environment Information
•$HOME: The current user's home directory.
•$PATH: The list of directories the shell searches for
commands.
•$USER: The name of the currently logged-in user.
•$SHELL: The shell program being used (e.g., /bin/bash).

Page - 22
4. Script and Command Execution
•$-: The current shell options.
•$_: The last argument of the last command.

Page - 23
Other Useful Variables
•$IFS: The Internal Field Separator, used for splitting strings (default is space,
tab, newline). Commonly used when reading files or processing input.
•$RANDOM: Generates a random number.
•$LINENO: The current line number in a script. Useful for debugging.

Page - 24
Manage Empty Variables

● Several parameter expansions are intended to deal with nonexistent and empty variables.
${parameter:-word}
● If parameter is unset (i.e., does not exist) or is empty, this expansion results in the value of
word.
● If parameter is not empty, the expansion results in the value of parameter.

Page - 25
Using Shell Arrays
● Arrays are variables that hold more than one value at a time.
● An array has cells, which are called elements, and each element contains data.
● An individual array element is accessed using an address called an index or subscript.
● Most programming languages support multidimensional arrays. Arrays in bash are limited to a
single dimension.

● There are two types of arrays we can create


- indexed arrays: array elements are stored with the index starting from zero
- associated arrays: array is stored with key-value pairs

Page - 26
Creating an array
● Array variables are named just like other bash variables and are created automatically when they
are accessed.
● Values may be assigned in one of two ways:
1. syntax: name[subscript]=value
2. syntax: name=(value1 value2 ...)
● An array can also be created with the declare command.

indexed array
Page - 27
associated array
Array Operations

1. Outputting the Entire Contents of an Array:


The subscripts * and @ can be used to access every element in an array.
The behavior of notations ${animals[*]} and ${animals[@]} is identical until they are quoted.
The * notation results in a single word containing the array’s contents, while the @ notation
results in three two-word strings, which matches the array’s “real” contents.
[root@localhost ~]# for i in "${A[@]}";do echo "$i";done [root@localhost ~]# for i in "${A[*]}";do echo "$i";done
98 98 5 9
5
9

‫* ﻓﻲ‬, @ ‫ اﻟﻔﺮق ﻣﺎ ﺑﻴﻦ‬For LOOP

Page - 28
Page - 29
Array Operations cont.

2. Determining the Number of Array Elements


The number of elements in an array can be determined in much the same way as finding
the length of a string.
Ex: $ echo ${#a[@]} # number of array elements
While: $ echo ${#a[100]} # length of element in index 100
● The behavior of array in other languages in which the unused elements of the array
would be initialized with empty values and counted.
● In bash, array elements exist only if they have been assigned a value regardless of
their subscript.

Page - 30
Array Operations cont.

3. Finding the Subscripts Used by an Array


● As bash allows arrays to contain “gaps” in the assignment of
subscripts, it is sometimes useful to determine which elements
actually exist.
● This can be done with a parameter expansion using the following
forms:
${!array[*]} or ${!array[@]}

Page - 31
Array Operations cont.

4. Adding Elements to the End of an Array


● Knowing the number of elements in an array is no help if we need to append values to the
end of an array since the values returned by the * and @ notations do not tell us the
maximum array index in use.
● By using the += assignment operator, we can automatically append values to the end of an
array.

- Any reference to an array variable without a subscript refers to element zero of the array.

Page - 32
Array Operations cont.

5. Sorting an Array
● The shell has no direct way of doing this, but it’s not hard to do with a little coding.

Page - 33
Array Operations cont.

6. Deleting an Array
To delete entire array, use the unset command.

unset may also be used to delete single array elements.

Page - 34
Shell Basic Operators
1. Arithmetic Operators

Page - 35
Assignment Operators

Page - 36
Relational Operators

Page - 37
Boolean Operators

Page - 38
String Operators

Page - 39
File Test Operators

Page - 40
Bit Operators

Page - 41
Shell Decision Making
1. Basic if statement

To run script

OR

Page - 42
Shell Decision Making cont.

2. if...else statement

Page - 43
Shell Decision Making cont.
3. if...elif...else statement

Page - 44
The case...esac Statement
Ex: determine file type

•The variable is matched against different patterns.


•The ;; ends each case block.
•The * acts as the default case, matching anything not listed.
•The esac closes the case statement.
Page - 45
Quiz time
1- How do you define an array in Bash?
A) array = [1,2,3] B) array=(1 2 3) C) array = {1 2 3} D) array = (1,2,3)
2- How do you access the second element of an array in Bash?
A) ${array[1]} B) ${array(1)} C) $array[2] D) array.get(2)
3- How do you print all elements of an array in Bash?
A) echo ${array[@]} B) echo array[] C) echo array{*} D) echo (${array})
4- : What is the correct syntax for performing arithmetic in Bash?
A) result=$((5 + 3)) B) result=(5 + 3) C) result=5 + 3 D) result=math.add(5,3)
5- How do you check if a file exists in Bash?
A) [ -file file.txt ] B) [ -e file.txt ] C) if exists file.txt D) if file.txt then

Q2. Write a shell script to calculate the string Length


Q3. Write a shell script to generate random number then print the PID for current script

Page - 46
Quiz time
1- How do you define an array in Bash?
A) array = [1,2,3] B) array=(1 2 3) C) array = {1 2 3} D) array = (1,2,3)
2- How do you access the second element of an array in Bash?
A) ${array[1]} B) ${array(1)} C) $array[2] D) array.get(2)
3- How do you print all elements of an array in Bash?
A) echo ${array[@]} B) echo array[] C) echo array{*} D) echo (${array})
4- : What is the correct syntax for performing arithmetic in Bash?
A) result=$((5 + 3)) B) result=(5 + 3) C) result=5 + 3 D) result=math.add(5,3)
5- How do you check if a file exists in Bash?
A) [ -file file.txt ] B) [ -e file.txt ] C) if exists file.txt D) if file.txt then

Q3. #!/bin/bash
Q2. #!/bin/bash
word="String" echo "Random number: $RANDOM"

echo "The length of '$word' is ${#word}“ echo "Current script PID: $$"
Page - 47
What will be the output of this script?
2. #!/bin/bash
text="ShellScripting"
1. #!/bin/bash
echo "Substring: ${text:3:5}“
colors=("Red" "Green" "Blue") echo “Substring: ${text: 5}”
for color in "${colors[@]}"; do Expected Output:

echo "Color: $color“


3. #!/bin/bash
done
ls /non_existent_directory
Expected Output:
echo "Exit status: $?“
Expected Output:

Page - 48
What will be the output of this script?
2. #!/bin/bash

1. #!/bin/bash text="ShellScripting"

colors=("Red" "Green" "Blue") echo "Substring: ${text:3:5}“


for color in "${colors[@]}"; do echo “Substring: ${text: 5}”
echo "Color: $color“ Expected Output:
done Substring: llScr
Expected Output:
3. #!/bin/bash Substring: Scripting
Color: Red
ls /non_existent_directory
Color: Green
Color: Blue echo "Exit status: $?“
Expected Output:

Page - 49
Exit status: 2
orl

Thank you !

Get ready loops and functions next week!

You might also like