0% found this document useful (0 votes)
8 views56 pages

Linux Shell Scripting Basics Guide

The document provides an overview of shell scripting in Linux, focusing on syntax, variable declaration, and environment variables. It explains how to create and execute shell scripts using the BASH shell, including the use of variables and command-line arguments. Additionally, it includes practical examples and exercises for creating scripts that utilize user input and environment variables.

Uploaded by

ubuntucyber6
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)
8 views56 pages

Linux Shell Scripting Basics Guide

The document provides an overview of shell scripting in Linux, focusing on syntax, variable declaration, and environment variables. It explains how to create and execute shell scripts using the BASH shell, including the use of variables and command-line arguments. Additionally, it includes practical examples and exercises for creating scripts that utilize user input and environment variables.

Uploaded by

ubuntucyber6
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

BNCS2115 – LINUX ADMINISTRATION

SHELL SCRIPTING
Topic: Shell Scripting and Syntax

Mr. Okello Ronald [Link], MSc. Cyber Security, Certified in Cyber Security, Instructor
Copyright 2023 ©, ISBAT University, All rights reserved.
SHELL SCRIPTING
2

Learning Outcomes
 Shell Syntax
 Variable Declaration
 Setting the Script Execution Path
 Environment Variables

© ISBAT UNIVERSITY – 2023 12/12/2023


Introduction
3

 A shell, by definition, is an interpretive environment


within which you execute commands.
 You can have many environments running at the
same time, of either the same or different types of
shells; you can have several shells running at the
same time that are of the BASH shell type.
 Usually, the instructions making up a shell program
are entered into a script file that can then be
executed.

© ISBAT UNIVERSITY – 2023 12/12/2023


Introduction
4

 This chapter will cover the basics of creating a shell


program using the BASH.
 The BASH shell has a flexible and powerful set of
programming commands that allows you to build
complex scripts. It supports variables that can be
either local to the given shell or exported to other
shells. You can pass arguments from one script to
another. The BASH shell has a complete set of
control structures, including loops and if statements
as well as case structures.

© ISBAT UNIVERSITY – 2023 12/12/2023


Introduction
5

 Shell variable, you can hold data that you


can reference over and over again as you execute
different commands within a given shell.
 You define variables within a shell, and such

variables are known as shell variables

© ISBAT UNIVERSITY – 2023 12/12/2023


Environment Variables
6

 When you log in to your account, your Linux system


generates your user shell. Within this shell, you can
issue commands and declare variables. You can also
create and execute shell scripts. The variable
created depends on personal configuration. The
main common ones are
Environment Variable Description

$HOME Home Dir of the Current User

$PATH A Colon: Separated list of


Directories to search for command

© ISBAT UNIVERSITY – 2023 12/12/2023


Environment Variables
7

Environment Varibales Description


$PS1 Primary shell prompt
BASH Holds full pathname of BASH command
SHELL Pathname of program for type of shell
you are using
PS2 Secondary shell prompt
CDPATH Search path for the cd command
TERM Terminal type
USER Username
UID Real user ID (numeric)
LOGNAME Login name
MAIL Name of specific mail file checked by
Mail utility for received messages, if
MAILPATH is not set

© ISBAT UNIVERSITY – 2023 12/12/2023


Setting up the Execution Path
8

 If you want to execute one of your own scripts or


programs in your working directory, the shell can
locate it. No spaces are allowed between the
pathnames in the string
 $ echo $PATH
 PATH=$PATH:$HOME/ShellScript:
 $ export PATH
 $ echo $PATH

© ISBAT UNIVERSITY – 2023 12/12/2023


Definition and Evaluation of Variables
9

 You define a variable in a shell when you first use


the variable’s name. A variable’s name may include
the following Character;
 any set of alphabetic characters, including the
underscore.
 A number, but the number cannot be the first
character in the name.
 Variable name should not have any
 an exclamation point, an ampersand, or even a
space, more than one word.
© ISBAT UNIVERSITY – 2023 12/12/2023
Definition and Evaluation of Variables
10

 You assign a value to a variable with the


assignment operator (=). You type the variable
name, the assignment operator, and then the value
assigned.
 Do not place any spaces around the assignment
operator. The assignment operation course = Linux,
for example, will fail.
 You can assign any set of characters to a variable.
In the next example, the variable course is assigned
the string Linux: $ course=Linux
© ISBAT UNIVERSITY – 2023 12/12/2023
Definition and Evaluation of Variables
11

 Once you have assigned a value to a variable, you


can then use the variable name to reference the
value.
 Use dollar to reference a variable’s value: The
Dollars sign is a special operator that uses the
variable name;
 Syntax: $ echo $course
 Wherever a $ is placed before the variable name,
the variable name is replaced with the value of the
variable.
© ISBAT UNIVERSITY – 2023 12/12/2023
Definition and Evaluation of Variables
12

 In the next example, the shell variable course is


evaluated and its contents, Linux, are then used as
the argument for an echo command. The echo
command simply echoes or prints a set of characters
to the screen.
 If you leave out the $ operator before the variable
name, all you have is the variable name itself.

© ISBAT UNIVERSITY – 2023 12/12/2023


Variable Values: Strings
13

 If you want to assign more than one word to a


variable, you need to quote the spaces separating
the words. You can do so by enclosing all the words
within double quotes.
 In this first example, the double quotes enclose
words separated by spaces. Because the spaces are
enclosed within double quotes, they are treated as
characters
 $ notice="The meeting will be tomorrow“
 $ echo $notice
© ISBAT UNIVERSITY – 2023 12/12/2023
Variable Values: Strings
14

 In the second example, double quotes also enclose


a period, treating it as just a character.
 $ message="The project is on time."
 $ echo $message
 In the third example, an asterisk is also enclosed
within the double quotes. The asterisk is considered
just another character in the string and is not
evaluated.
 $ notice="You can get a list of files with ls *.c"
 echo $notice
© ISBAT UNIVERSITY – 2023 12/12/2023
Variable Values: Strings
15

 However, do not quote the dollar sign, the operator


that evaluates variables. A $ operator next to a
variable name enclosed within double quotes will
still be evaluated, replacing the variable name with
its value.
 winner=ruth
 notice="The Person who Won is $winner"
 echo $notice
 Single quotes suppress any variable evaluation and
treat the dollar sign as just another character

© ISBAT UNIVERSITY – 2023 12/12/2023


Variable Values: Strings
16

 winner=ruth
 message='The Name is in the $winner
Variable'
 $ echo $message
 The backslash is useful when you want to both
evaluate variables within a string and include the $
character
 winner=ruth
 $ result="$winner won \$100.00„
 echo $result
© ISBAT UNIVERSITY – 2023 12/12/2023
Create and Run Your First Bash Shell Script
17

 Let’s first create a new directory named scripts that


will host all our bash scripts.
 Mkdir ShellScript
 cd ShellScript

 nano/vi [Link]

 Make its excutable

 chmod u+x [Link]

 Run using bash [Link] or


./[Link]
© ISBAT UNIVERSITY – 2023 12/12/2023
18

 “#!/bin/bash is referred to as the shebang line and


in some literature, it’s referred to as the hashbang
line and that’s because it starts with the two
characters hash ‘#’ and bang ‘!’
 “#!/bin/bash” at the very top of your script, the
system knows that you want to use bash as an
interpreter for your script. Thus, you can run the
[Link] script directly now without preceding it with
bash.

© ISBAT UNIVERSITY – 2023 12/12/2023


Using variables in bash shell scripts
19

 Let's improve this script the Hello world Script by


using shell variables so that it greets users with their
names. Edit your [Link] script
 #! /bin/bash
 echo "What's your name, stranger?"
 read name
 echo "Hello, $name"

© ISBAT UNIVERSITY – 2023 12/12/2023


Using variables in bash shell scripts
20

 #! /bin/bash
 echo “Please Enter a Greeting:"
 read greeting
 echo “The Greeting You Entered was
$ greeting "

© ISBAT UNIVERSITY – 2023 12/12/2023


Using variables in bash shell scripts
21

 Write a shell script in that prints your user name.


 Hint: Use echo command with USER environment
variable
 Syntax :#!/bin/bash
 echo "$USER"
 Write a shell script in that prints your current
working directory.
 Hint: Use echo command with PWD environment
variable.

© ISBAT UNIVERSITY – 2023 12/12/2023


Using variables in bash shell scripts
22

 Syntax: #!/bin/bash
 echo "$PWD"
 Write a shell script in that prints the absolute path
to your home directory.
 Hint: Use echo command with HOME environment
variable.
 Syntax: #!/bin/bash
 echo "$HOME"

© ISBAT UNIVERSITY – 2023 12/12/2023


Using variables in bash shell scripts
23

 Write a shell script in that prints the default shell.


Hint: Use echo command with SHELL environment
variable.
 Syntax: #!/bin/bash

echo "$SHELL"
 Write a shell script in that prints all of the above
four questions, i.e. your user name, current working
directory, home directory and default shell.
 Print all the answers in a separate line.

© ISBAT UNIVERSITY – 2023 12/12/2023


Using variables in bash shell scripts
24

 #!/bin/bash
 echo "Hello“
 echo "My name is $USER"
 echo "My current location is $PWD"
 echo "My home directory is $HOME"
 echo "My default shell is $SHELL"

© ISBAT UNIVERSITY – 2023 12/12/2023


shell script arguments
25

 In shell scripting, arguments are values that are


passed to a script or a function when it is executed.
 These values can be used as inputs for the script or
function to perform operations or make decisions.
 Shell scripts can take arguments in the form of
command line arguments or function arguments.
 Command line arguments are values that are
passed to a shell script when it is executed from the
command line. They are typically used to provide
inputs or options to the script.
© ISBAT UNIVERSITY – 2023 12/12/2023
shell script arguments
26

 Just as any Linux command can take arguments, so


also can a shell script.
 Arguments on the command line are referenced
sequentially starting with 1.
 An argument is referenced using the $ operator and
the number of its position. The first argument is
referenced with $1, the second with $2, and so on.
 Example

© ISBAT UNIVERSITY – 2023 12/12/2023


shell script arguments
27

 #!/bin/bash
 echo "Username: $1";
 echo "Age: $2";
 echo "Full Name: $3";
 When a Bash shell script is invoked, all the words on
the command line are parsed and placed in
elements of an array, array will hold the name of
the shell script, and beginning with $1, each
element will hold an argument entered on the
command line
© ISBAT UNIVERSITY – 2023 12/12/2023
shell script arguments
28

 Lets create a script lines_count_script.sh that will


print total number of lines present in whatever the
file user provides
 Create a file lines_count.txt which has five lines of
text.
 #!/bin/bash
 echo "Enter File to print the Count of
Line"
 read filename
 echo "The Number of line in $filename is
$(wc -l < $filename)"
© ISBAT UNIVERSITY – 2023 12/12/2023
shell script arguments
29

 #!/bin/bash
 echo "Enter File to print the
Count of Line"
 read filename
 echo "The Number of Lines in
lines_Count.txt $1 is $(wc -l <
$filename)"

© ISBAT UNIVERSITY – 2023 12/12/2023


Multiple shell script Argument
30

 The Bash shell uses a different set of argument


variables to reference arguments.
 These are very similar to those used in the C
programming language. When a Bash shell script is
invoked, all the words on the command line are
parsed and placed in elements of the variable $.
 The $1, hold an argument entered on the command
line.

© ISBAT UNIVERSITY – 2023 12/12/2023


Multiple shell script Argument
31

 .As with any array element, you can access the


contents of an argument array element by
preceding it with a $ operator.
 For example, $1 accesses the contents of the first
element in the array, the first argument.
 In the greetarg script, a greeting is passed as the
first argument on the command line. This first
argument is accessed with $1.
 #! /bin/bash
 echo "The Greeting You Entered was: $1"

© ISBAT UNIVERSITY – 2023 12/12/2023


Multiple shell script Argument
32

 #! /bin/bash
 echo "The Name of Your Script is :
$0"
 echo "The first argument is : $1"
 echo "The second argument is: $2"
 echo "The third argument is: $3"
 echo "The fourth argument is: $4"

© ISBAT UNIVERSITY – 2023 12/12/2023


Special variables in Bash shell:
33

Special Variable Description


$0 The Name of the Bash Script
$1,$2..$n The Bash Script Argument
$$ The Process ID of the current shell
$# The Total number of argument passed to a shell script
$@ The Value of all argument passed to a script
$? The Exit status of the last executed command
$! Process id of the executed command

© ISBAT UNIVERSITY – 2023 12/12/2023


Control Structures
34

 You can control the execution of Linux commands in a


shell script with control structures.
 Control structures allow you to repeat commands and to
select certain commands over others.
 There are two different kinds of control structures: loops
and conditions. A loop repeats commands, whereas a
condition executes a command when certain conditions
are met.
 The BASH shell has three loop control structures: while,
for, and for-in. There are two condition structures: if and
case
© ISBAT UNIVERSITY – 2023 12/12/2023
Control Structures
35

 All Linux commands return an exit status after they


have finished executing. If a command is successful,
its exit status will be 0.
 If the command fails for any reason, its exit status
will be a positive value referencing the type of
failure that occurred.
 The control structures check to see if the exit status
of a Linux command is 0 or some other value. In the
case of the if and while structures, if the exit status
is a 0 value, then the command was successful and
the structure continues.
© ISBAT UNIVERSITY – 2023 12/12/2023
Test Operations
36

 With the test command, you can compare integers,


compare strings, and even perform logical
operations. The command consists of the keyword
test followed by the values being compared,
separated by an option that specifies what kind of
comparison is taking place
 The option can be thought of as the operator, but it
is written, like other options, with a minus sign and
letter codes. For example, -eq is the option that
represents the equality comparison.

© ISBAT UNIVERSITY – 2023 12/12/2023


Test Operations
37

 However, there are two string operations that


actually use an operator instead of an option.
When you compare two strings for equality, you use
the equal sign (=). For inequality you use !=.
 Syntax: test value -option value
 test string = string
 num=5
 test $num -eq 10
 echo $?

© ISBAT UNIVERSITY – 2023 12/12/2023


Test Operations
38

Integer Comparison Function


-gt Greater-than
-lt Less-than
-ge Greater-than-or-equal-to
-le Less-than-or-equal-to
-eq Equal
-ne Not-equal
String Comparisons
-z Tests for empty string
= Tests for equality of strings
!= Tests for inequality of strings

© ISBAT UNIVERSITY – 2023 12/12/2023


Test Operations
39

Logical Operators Function


-a Logical AND
-o Logical OR
! Logical NOT
File Tests
-f File exists and is a regular file
-s File is not empty
-r File is readable
-w File can be written to and modified
-x File is executable
-d Filename is a directory name

© ISBAT UNIVERSITY – 2023 12/12/2023


Conditional Control Structures
40

 The BASH shell has a set of conditional control structures


that allow you to choose what Linux commands to
execute.
 Many of these are similar to conditional control structures
found in programming languages, but there are some
differences.
 The if condition tests the success of a Linux command, not
an expression. Furthermore, the end of an if-then
command must be indicated with the keyword fi, and the
end of a case command is
 indicated with the keyword esac.
© ISBAT UNIVERSITY – 2023 12/12/2023
Conditional Control Structures
41

 The condition control structures are listed in Table 4-


2.
 The if structure places a condition on commands.
That condition is the exit status of a specific Linux
command.
 If a command is successful, returning an exit status
of 0, then the commands within the if structure are
executed. If the exit status is anything other than 0,

© ISBAT UNIVERSITY – 2023 12/12/2023


Conditional Control Structures
42
Condition Control Function
Structures:
if command then if executes an action if its test command is true.
command
fi
if command then if-else executes an action if the exit status of its test
command command is true; if false, then the else action is
else executed.
command
fi

The if keyword is used to specify the condition, and


the then keyword is used to specify the action to be
taken if the condition is true

© ISBAT UNIVERSITY – 2023 12/12/2023


Conditional Control Structures
43

if condition
then statement1
else statement2
fi

Example
#!/bin/bash
#Check if a file exist in the Directory
if test -e
"/home/isbat/ShellScript/lines_count.txt";
then
echo "File exists"
else
echo "File does not exist"
fi
© ISBAT UNIVERSITY – 2023 12/12/2023
For loops
44

 For loops in Bash are used to iterate through a list


of items, such as files in a directory, and perform a
set of actions for each item in the list.
 The basic syntax for a Bash for loop is for var in list;
do commands; done.
 The var variable is set to each item in the list and
the commands are executed for each item.
 In Bash, list can be a range of numbers, a list of
filenames or directory names, or a list of strings
separated by spaces.
© ISBAT UNIVERSITY – 2023 12/12/2023
For loops
45

for variable in list-values for-in is designed for use with lists of


do values; the variable
command operand is consecutively assigned the
done values in the list.

for variable for is designed for reference script


do arguments; the variable
command operand is consecutively assigned each
done argument value.

© ISBAT UNIVERSITY – 2023 12/12/2023


For loops
46

 For loops can be extremely useful in automating


tasks that involve iterating through a large number
of items, such as renaming files or processing data
files.
 By using For loops, you can write more efficient and
effective scripts that can save you time and effort in
your daily tasks.
 The basic syntax of the for loop is as follows:

© ISBAT UNIVERSITY – 2023 12/12/2023


For loops
47

 for variable in list


 do
 statement
 done
 In this example, the script iterates through the items
in the list, assigns each item to the variable, and
executes statement for each item.

© ISBAT UNIVERSITY – 2023 12/12/2023


For loops
48

 Example 1
 #!/bin/bash
 for i in 1 2 3 4 5
 do
 echo $i
 Done
 In this example , the script iterates through the
numbers from 1 to 5 and prints each number using
the echo command

© ISBAT UNIVERSITY – 2023 12/12/2023


For loops
49

 Example 2
 #!/bin/bash
 for word in This is a sequence of
words
 do
 echo $word
 Done
 In this example, the script iterates through the words
and prints each word using the echo command

© ISBAT UNIVERSITY – 2023 12/12/2023


For loops
50

 Example 3
 #!/bin/bash
 for file in *.sh
 do
 ls -lh "$file"
 done
 In this example, the script iterates through the words
.sh list in current directory and list all script files
with filename pattern "*.sh"

© ISBAT UNIVERSITY – 2023 12/12/2023


For loops
51

 You can also use the for loop to iterate through the
items in an array:
 Example 1:
 #!/bin/bash
 array=(“Apple" “Oranges" “Guava")
 for i in "${array[@]}"
 do
 echo $i
 done
© ISBAT UNIVERSITY – 2023 12/12/2023
While loops
52

 While loops in Bash are used to execute a set of


commands repeatedly until a specific condition is
met.
 The basic syntax for a Bash while loop is while
condition; do commands; done.
 The commands within the loop are executed as long
as the condition is true.
 In Bash, condition can be a numeric or string
comparison, a file test, or any other command that
returns a true or false value.
© ISBAT UNIVERSITY – 2023 12/12/2023
While loops
53

while command while executes an action as long as its test command


do is true.
command
done

Syntax: while condition


do
statement
done

© ISBAT UNIVERSITY – 2023 12/12/2023


While loops
54

 Example 1
 #!/bin/bash
 i=1
 while [ $i -le 5 ]
 do
 echo $i
 i=$((i+1))
 done

 In this example, the script initializes i to 1, checks if i


is less than or equal to 5 using the -le option, prints
i, and increments i by 1 using the $((i+1)) syntax.
This process is repeated until i is greater than 5.
© ISBAT UNIVERSITY – 2023 12/12/2023
While loops
55

 Example 2
 #!/bin/bash
 while read line
 do
 echo $line
 done <
/home/isbat/ShellScript/lines_count.txt
 in this example, the script reads each line from the
lines_count.txt file using the read command and
assigns it to the line variable. It then prints each line
using the echo command.
© ISBAT UNIVERSITY – 2023 12/12/2023
56

QUESTIONS ??

END
Thank you
© ISBAT UNIVERSITY – 2023 12/12/2023

You might also like