Week 9 Lecture Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

ULI101: INTRODUCTION TO UNIX / LINUX AND THE INTERNET

WEEK 9 LESSON 1

INTRODUCTION TO SHELL SCRIPTING /


CREATING SHELL SCRIPTS
SHELL VARIABLES

PHOTOS AND ICONS USED IN THIS SLIDE SHOW ARE LICENSED UNDER CC BY-SA
LESSON 1 TOPICS

Shell Scripts
• Purpose
• Considerations When Creating Shell Scripts
• Creating Shell Scripts

Shell Variables
• Purpose
• Environment Variables
• User Defined Variables

Perform Week 10 Tutorial


• Investigation 1
• Review Questions (Questions xx - xx)
SHELL SCRIPTING

Definition

A shell script is a computer program designed to be run by


the Unix shell, a command-line interpreter. The various dialects
of shell scripts are considered to be scripting languages.

Typical operations performed by shell scripts include


file manipulation, program execution, and printing text.

Reference: https://en.wikipedia.org/wiki/Shell_script
SHELL SCRIPTING

Considerations When Creating Shell Scripts

The reason to create shell scripts is to automate the


execution of commonly issued Linux commands and tasks.

Prior to simply placing Linux commands in a file to run, you


should plan-out the purpose of the shell script and list the
steps that you want to accomplish. This will help to lists the
sequence of steps required to ensure that your shell script
is successful
SHELL SCRIPTING

Creating a Shell Script

Once you have planned your shell script by listing the


sequence of steps in your script, you need to create a file
that will contain your Linux commands.

NOTE: Avoid using filenames of already existing Linux


Commands to avoid confusion. Using shell script filenames
that include the file extension of the shell that the script will
run within is recommended.

Examples:
clean-directory.bash
copy-directory-structure.sh
SHELL SCRIPTING

Creating a Shell Script

The Shebang Line


If you are learning Bash scripting by reading other people’s code
you might have noticed that the first line in the scripts starts with
the #! characters and the path to the Bash interpreter.
This sequence of characters (#!) is called shebang and is used to
tell the operating system which interpreter to use to parse the rest
of the file.

Reference: https://linuxize.com/post/bash-shebang/
SHELL SCRIPTING

Creating a Shell Script

Examples of Shebang Line


#!/bin/bash
#!/bin/csh

You can use the which command to determine the full pathname
of the shell. For example: which bash

The shebang line must appear on the first line and at the beginning
of the shell script, otherwise, it will be treated as a regular comment
and ignored.
SHELL SCRIPTING

Creating a Shell Script

Displaying Text: The echo Statement


The echo command is used to display text.

Example:

echo This is some text


SHELL SCRIPTING

Creating a Shell Script

Prompting User Input: The read Statement


The read command pauses and waits for a user to
enter data and then stores into a variable when the
user presses the ENTER key.

Example:

read –p “Enter your name: ”


age echo “Your age is $age”

Note: Placing a dollar sign ($) in front of variable


name expands the value stored in the varaiable.
SHELL SCRIPTING

Creating a Shell Script

Setting Script Permissions & Running Script

To run your shell script by name, you need to assign execute


permissions for the user. To run the shell script, you can execute
it using a relative, absolute, or relative-to-home pathname

You can run a shell script that does not have permissions by issuing
Example: the shell command with the shell script as an argument.

chmod u+x myscript.bash Example:

./myscript.bash bash ./myscript.bash

/home/username/myscript.bash
You can add the directory that contains the shell script so it can be issued
~/myscript.bash by just name and not pathname by adding the directory pathname into the
PATH environment variable

Example:
PATH=$PATH:directory-pathname
SHELL SCRIPTING

Creating Shell Scripts


Instructor Demonstration

Task1:

Create a Bash Shell script to clear the screen and then display all
users that are logged onto the system.

Task2:

Create a Bash Shell script to clear the screen, prompt the user for
their full name, and then display the text message:
Hello, your name is (your full name)
SHELL SCRIPTING

Using Variables

Variables are used to store information to be referenced and


manipulated in a computer program. They also provide a way
of labeling data with a descriptive name, so our programs can
be understood more clearly by the reader and ourselves.
It is helpful to think of variables as containers that hold
information. Their sole purpose is to label and store data in
memory. This data can then be used throughout your program.

Reference: https://launchschool.com/books/ruby/read/variables
SHELL SCRIPTING

Using Variables

Shell variables are classified in 2 groups:

System (shell) variables: describing the working environment


User-created variables: associated with scripts

Variables can be read/write or read-only

The name of a variable can be any sequence of letters and numbers,


but it must NOT start with a number
SHELL SCRIPTING

Environment Variables
Shell environment variables shape the working environment whenever you are logged
in Common shell. Some of these variables are displayed in the table below (you can
issue the pipeline command set | more to view all variables)

Variable Name Purpose


PS1 Primary shell prompt
PWD Absolute path of present working directory
HOME Absolute path to user's home
PATH List of directories where commands / programs are located
HOST Host name of the computer
USER Name of the user logged in
SHELL Name (type) of current shell used
SHELL SCRIPTING

Environment Variables

Placing a dollar sign ($) prior to the variable name


will cause the variable to expand to the value
contained in the variable.

Examples:
echo “My current location is:
$PWD” who | grep $USER
echo $HOST
SHELL SCRIPTING

The PATH Environment Variable

PATH is an environment variable present in Unix/Linux operating


systems, listing directories where executable programs are located.
Multiple entries are separated by a colon (:)
The shell searches these directories whenever a command is invoked
in the sequence listed. In case of multiple matches use the which utility
to determine which match has a precedence
On some systems the present working directory may not be included
in the PATH by default
To run shell scripts the user can issue using the ./ prefix or the
user can modify the PATH variable if they want to issue the shell
script without the ./ prefix.
SHELL SCRIPTING

User Defined (Created) Variables

User-defined variables are variables which can


be created by the user and exist in the session.

This means that no one can access user-defined


variables that have been set by another user, and when
the session is closed these variables expire.

Reference: https://mariadb.com/kb/en/user-defined-variables/
SHELL SCRIPTING

User Defined Variables

Assigning a Value to a User Defined Variable:

name=value

If a variable’s value contains spaces or tabs, they should


be surrounded by quotes

Example:

phone="1 800 123-4567"


SHELL SCRIPTING

User Defined Variables

Removing a Value from a User Defined Variable:

name=

OR
unset name

Examples:

customerName=
unset userAge
SHELL SCRIPTING

User Defined (Created) Variables

Including the keyword readonly before the command assignment prevents you
from changing the variable afterwards

Examples:
name=“Murray Saul”
readonly name
readonly phone="123-4567"

If no variable name is supplied a list of defined read only variables will be displayed.

NOTE: Read-only variables cannot be removed – you must log out for them to
be cleared
SHELL SCRIPTING

Getting Practice
To get practice to help perform assignment #3, perform Week 10 Tutorial:

• INVESTIGATION 1

• LINUX PRACTICE QUESTIONS (Questions xx – xx)


ULI101: INTRODUCTION TO UNIX / LINUX AND THE INTERNET

WEEK 9: LESSON 2

POSITIONAL PARAMETERS
TEST STATEMENT / CONTROL FLOW STATEMENTS (LOGIC / LOOPS)

PHOTOS AND ICONS USED IN THIS SLIDE SHOW ARE LICENSED UNDER CC BY-SA
LESSON 2 TOPICS

Positional Parameters
• Purpose
• Usage

Control Flow Statements


• Purpose
• Exit Status $? / Using the test statement
• Control Flow Statements (Conditionals, Loops)

Perform Week 10 Tutorial


• Investigation 2
• Review Questions (Questions xx – xx)
POSITIONAL PARAMETERS
arg1 arg2 arg3 … argN

A positional parameter is a variable within a shell program;


its value is set from an argument specified on the command
line that invokes the program.

Positional parameters are numbered and are referred


to with a preceding ``$'': $1, $2, $3, and so on.

Reference: http://osr600doc.xinuos.com/en/SDK_tools/_Positional_Parameters.html
POSITIONAL PARAMETERS
arg1 arg2 arg3 … argN

Assigning Values as Positional Parameters

There are a few ways to assign values as positional parameters:

• Use the set command with the values as argument after the
set command

• Run a shell script containing arguments


POSITIONAL PARAMETERS
arg1 arg2 arg3 … argN

Using the set command:

set apples oranges bananas

You place a dollar sign ($) prior to the number


corresponding to the position of the argument

Examples:
echo $1
echo $2
echo $3
POSITIONAL PARAMETERS
arg1 arg2 arg3 … argN

Running a Shell Script with Arguments:

You would use positional parameters in your shell script that would
expand the positional parament with its stored value.

Here are the contents of the shell script called myScript.bash:

#!/bin/bash

echo “First argument is $1”


echo “Second argument is $2”

You would then issue the myScript.bash shell script with


arguments that would be used within the shell script. For Example:
./mySript.bash My-First-Argument My-Second-Argument
POSITIONAL PARAMETERS
arg1 arg2 arg3 … argN

Command line parameters are referred to as $0…$9


The positional parameter $0 refers to either the name of shell where
command was issued, or name of shell script being executed.

If using positional parameters greater than 9, then you need to include


number within braces.

Examples:
echo ${10}
ls ${23}
POSITIONAL PARAMETERS
arg1 arg2 arg3 … argN

The shift command can be used with positional


parameters to shift positional parameters to the left
by one or more positions.

Examples:

shift
shift 2
SPECIAL PARAMETERS
$* $# $?

There are a group of special parameters that can be used for


shell scripting. A few of these special parameters and their
purpose are displayed in the table below.

Parameter Purpose
$* Display all positional parameters.

“$*” Containing values of all arguments separated by a single space


“$@” Multiple double-quoted strings, each containing the value of
one argument
$# Represents the number of parameters
(not including the script name)
$? Exit Status of previous command (discussed in next lesson)
POSITIONAL AND SPECIAL PARAMETERS

Positional and Special Parameters


Instructor Demonstration
CONTROL FLOW STATEMENTS

So far, we have created Bash Shell Scripts that executed


Linux commands in a fixed sequence.

Although those type of scripts can be useful, we can use


control flow statements that will control the sequence of
the running script based on various situations or conditions.

Control Flow Statement are used to make your shell


scripts more flexible and can adapt to changing situations.
CONTROL FLOW STATEMENTS

The “$?” Special Parameter

The special parameter $? Is used to determine the exit status of


the previously issued Linux command.

The exit status will either display a zero (representing TRUE) or a non-
zero number (representing FALSE). This can be used to determined if
a Linux command was correctly or incorrectly executed.

Examples:

PWD
echo $?
pwd
echo $?
CONTROL FLOW STATEMENTS

The test Linux Command

The test Linux command is used to test conditions to see if they


are TRUE (i.e. value zero) or FALSE (i.e. value non-zero)
so they can be used with control flow statements to control
the sequence of a shell script.

Examples:
name=“Murray”
test $name = “Murray”
echo $?
test $name = “David”
echo $?
CONTROL FLOW STATEMENTS

The test Linux Command – Numerical Comparison

You CANNOT use the > or < symbols when using the test
command since these are redirection symbols. Instead, you
need to use options when performing numerical comparisons.
Refer to the table below for test options and their purposes.

Option Purpose
-eq Equal to
-ne Not equal to
-lt , -le Less than, Less than or equal to
-gt, -ge Greater than, greater than or equal to
CONTROL FLOW STATEMENTS

The test Linux Command – Additional Options

There are other comparison options that can be used with the
test command such as testing to see if a regular file or directory
pathname exists, or if the regular file pathname is –non-empty.

Below are some of those options.

Option Purpose
-f file_pathname Regular filename exists
-d file_pathname Directory filename exists
-s file_pathname Regular filename is non-empty
-w file_pathname file exists / write permission is granted
CONTROL FLOW STATEMENTS

Logic Statements

A logic statement is used to determine which Linux


commands to be executed based on the result of a condition
(i.e. TRUE (zero value) or FALSE (non-zero value)).

There are several logic statements, but we will just


concentrate on the if statement.

if test condition
then
command(s)
fi
CONTROL FLOW STATEMENTS

Logic Statements

If the test condition returns a TRUE value,


then the Linux Commands between then
and fi statements are executed.

If the test returns a FALSE value, then the


if statement is bypassed.
Example:
num1=5
num2=10
if test $num1 –lt $num2
then
echo “Less Than”
fi
CONTROL FLOW STATEMENTS

Logic Statements

The set of square brackets [ ] can be used to


represent the test command.

NOTE: There must be spaces between the


square brackets and the test condition.

Example:
num1=5
num2=10
if [ $num1 –lt $num2 ]
then
echo “Less Than”
fi
CONTROL FLOW STATEMENTS

Loop Statements

A loop statement is a series of steps or sequence of


statements executed repeatedly zero or more times
satisfying the given condition is satisfied.

Reference:
https://www.chegg.com/homework-help/definitions/loop-statement-3
CONTROL FLOW STATEMENTS

There are several loops, but we will look at the loop


for using a list.

for item in list


Variable "item" will hold one item from the
do list every time the loop iterates (repeats).

command(s) A list can consist of a series of arguments


(separated by spaces) or supplied by a command
done
CONTROL FLOW STATEMENTS

Example:

for x in apples oranges


bananas do
echo “The item is: $x”
done
CONTROL FLOW STATEMENTS

Instructor Demonstration

Your instructor will demonstrate examples of


using control flow statements.
REGULAR EXPRESSIONS

Getting Practice
To get practice to help perform assignment #2, perform Week 10 Tutorial:

• INVESTIGATION 2

• LINUX PRACTICE QUESTIONS (Questions xx – xx)

You might also like