lecture 6
lecture 6
● 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.
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
• 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
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
#!/usr/bin/env bash
• 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
• 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
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
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
Page - 17
Read-only Variables
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.
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
Page - 28
Page - 29
Array Operations cont.
Page - 30
Array Operations cont.
Page - 31
Array Operations cont.
- 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.
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
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:
Page - 48
What will be the output of this script?
2. #!/bin/bash
1. #!/bin/bash text="ShellScripting"
Page - 49
Exit status: 2
orl
Thank you !