0% found this document useful (0 votes)
5 views24 pages

ITNB3143 Operating Systems - Lesson7 ShellProgramming

Operating Systems
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)
5 views24 pages

ITNB3143 Operating Systems - Lesson7 ShellProgramming

Operating Systems
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

Lesson 7 TOPIC: Shell Programming • To understand the difference CLO2, CLO3

• Variables between local and global


• Parameters variables.
• Condition Statements and Loops • To be able to write shell script
programming
• To be able to use the if and
if-else selection statements to
choose among alternative
actions
• To be able to use the while
repetition statement to
execute statements in a
program repeatedly.

Why This Lesson

This chapter helps to understand the architecture of Linux Operating System, basic command, install the Linux
operating system and shell programming.

How to Install Linux Operating System

Watch and install according to your Operating System.


[Link]

Introduction

Linux is a Unix-like computer operating system designed by Linus Torvalds. It was released on 5 October 1991,
when Torvalds was still a student at the University of Helsinki, Finland. Linux is free and an open source operating
system software, that is free to use, modify and distribute both commercially and non-commercially. Anyone
with licenses such as the GNU General Public License can modify and improve the program as per their
requirement. They can even release their improved version to the public.

Linux is also a multitasking, multi-user operating system which means that many people can run many different
applications on one computer at the same time. This differs from MS-DOS, where only one person can use the
system at a particular time. When many people are working then each user is identified by the system through
their unique Login Id and Password.
Debian, Red Hat Enterprise Linux, Mandriva, open SUSE and Arch Linux are popular Linux distributions. More than
90% of the world’s fastest supercomputers including the top 10 fastest supercomputers run on some variant of
Linux.

Some key features of Linux are:

Multi-user operating system: Linux support multiple users at one time. In this type of operating system, there is a
server and all the users are provided with different terminals.

Free and open source: It means it is free software which can easily be downloaded from the Internet and
anybody can use and modify it as per their requirement.

© UNITAR International University 1 Prepared by: Shaheeda Begum


Multitasking: Linux allows more than one program to run at a time. The user can create a word document and
at the same time, can download files from the Internet and also get the printing done.

Multiplatform: Linux operating system can run on many different computer platforms.

Security: Linux is one of the most secure operating systems. File access permission systems prevent access by
unwanted visitors or viruses.

Shell: Linux provides a special interpreter program which is used to execute commands of the operating s

Components of Linux:
Linux system is divided into the following major components/Layers

The architecture of the Linux System consists of the following layers:

1. Hardware: Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
2. Kernel: It is the core component of the Operating System, interacts directly with hardware, and provides
low-level services to upper-layer components.
3. Shell: An interface to the kernel, hiding the complexity of the kernel's functions from users. The shell takes
commands from the user and executes the kernel's functions.

© UNITAR International University 2 Prepared by: Shaheeda Begum


4. Utilies: Utility programs that provide the user with most of the functionalities of an operating system.

Linux Command
A Linux command is a program or utility that runs on the CLI – a console that interacts with the system via texts
and processes. It’s similar to the Command Prompt application in Windows.

Linux commands are executed on the Terminal by pressing Enter at the end of the line. You can run commands
to perform various tasks, from package installation to user management and file manipulation.

Linux Command Syntax:


CommandName [option(s)] [parameter(s)]

A command may contain an option or a parameter. In some cases, it can still run without them. These are the
three most common parts of a command:
• CommandName is the rule that you want to perform.
• Option or flag modifies a command’s operation. To invoke it, use hyphens (–) or double hyphens (—).
• The parameter or argument specifies any necessary information for the command.

Command Description Example


whoami Which account you are using

pwd Print or list the present working directory


with a full path

mkdir Create the directory(ies). If they do not


already exist
Options:
-p,--parents: no error if exits, make
parent directories as needed
cd Change the current directory. With no
arguments "cd" changes to the user's
home directory. (cd <directory path>)

© UNITAR International University 3 Prepared by: Shaheeda Begum


ls List information about the FILEs (the
current directory by default).
Options:
ls, ls-a ,ls –l , ls-lh, ls –al, ls –ld, ls –r).
-a, --all
do not ignore entries starting with .`

rmdir is used to remove an empty directory.

Touch To create an empty file (s) Single file:

Multiple files

© UNITAR International University 4 Prepared by: Shaheeda Begum


rm The rm (short for "remove") command is
used to remove a file. Unlike some
graphical user interfaces, the command
line in general does not have a waste
bin or trash can to recover files. When
you use rm to remove a file, the file is
gone. Therefore, be careful when
removing files!

Cat concatenate files and print on the


Note: cril + standard output
D to exit Ex cat>file1
from the file Create a new file

To append the content

To view the content of a file

cp The cp command creates a copy of a


file for you

Ps shows you processes running on the


machine (sort of like the Window Task
Manager)

© UNITAR International University 5 Prepared by: Shaheeda Begum


grep The grep filter searches a file for a
particular pattern of characters, and
displays all lines that contain that
pattern.

man man is the system's manual pager.

Editors:

Linux text editors can be used for editing text files, writing codes, updating user instruction files, and more. A
Linux system supports multiple text editors. There are two types of text editors in Linux, which are given below:

o Command-line text editors such as Vi, nano, pico, vim and more.

o GUI text editors such as gedit (for Gnome), Kwrite, and more.

© UNITAR International University 6 Prepared by: Shaheeda Begum


syntax
<editorname <[Link]>

Example: How to work on editors?


Step1: nano [Link]
Step2: Write code in the editor
Step3: save and exit
Press esc :wq
Step4: run the file

Control Operators
▪ semicolon(;): You can put two or more commands on the same line separated by a semicolon(;). The
shell will scan the line until it reaches the semicolon. All the arguments before this semicolon will be
considered as a separate command from all the arguments after the semicolon. Both series will be
executed sequentially with the shell waiting for each command to finish before starting the next one.
▪ ampersand (&): When a line ends with an ampersand &, the shell will not wait for the command to
finish. You will get your shell prompt back, and the command is executed in the background.
▪ double ampersand (&&): The shell will interpret && as a logical AND. When using && the second
command is executed only if the first one succeeds (returns a zero exit status).
▪ double vertical bar (||): The || represents a logical OR. The second command is executed only when
the first command fails (returns a non-zero exit status).
▪ pound sign (#): Everything written after a pound sign (#) is ignored by the shell. This is useful to write a
shell comment but does not influence the command execution or shell expansion.

Linux File Management and View


Every Linux/Unix account is assigned a specific user number and a group number. This is how the system
identifies the user. Therefore, 2 accounts with different usernames but the same user number would be
considered by the system to be the same id. These user and group numbers are what Linux/Unix uses to
determine file and directory access privileges.
Linux/Unix has three different file/permissions: read, write and execute.
1. Read: Allows a user to view the contents of the file.
2. Write-Allows a user to change the contents of the file.
3. Execute- Allows a user to execute a file ( if it is an executable type of file; otherwise, the user will get an
error when they are trying to execute it)

File/DirectoryPermissions
There are two methods to assign permission to a file/directory they are :

1. Symbolic method: In the symbolic method, symbols are used to change file/directory permissions. Three
access rights are used that is {r, w, x} for read, write and execute respectively. The access classes used
are user (u), group (g), and others (o). The symbol (+) is used for adding permission, (-) for removing
permission, and (=) for assigning new permission.

© UNITAR International University 7 Prepared by: Shaheeda Begum


File User Group others

-
Read and write Read only Read only

Directory User Group others

-
Read, write and Read and execute Read and execute
execute

Changing ownership and Group


Syntax:

chmod [u, g, or o] [+ or -] [rwx] [file/directory name]


The following abbreviations are used:
▪ u -User (the file or directory's owner)
▪ g -Group (members of the owner's group)
▪ o -Others (all others)
▪ r -Read permission
▪ w -Write permission
▪ x -Execute permission

Example1: Changine group permission to read, write and execute on file1

© UNITAR International University 8 Prepared by: Shaheeda Begum


Example2: Assigning other to execute permission and delete the user write permission on file1

2. Absolute/Octal method: Works by specifying a numeric argument for the permissions for which you wish
to change. Example: 777 means user, group and others have read, write and execute permissions.

Binary Value Permission Description


000 0 --- No permission
001 1 --x Execute Only
010 2 -w- Write only
011 3 -wx Write and execute
100 4 r-- Read only
101 5 r-x Read and execute
110 6 rw- Read and write
111 7 rwx Read ,write and
exeute

Example: Assign user read write execute, group read write and others read and execute on file2.

© UNITAR International University 9 Prepared by: Shaheeda Begum


Sol:

Variables

Introduction to Shell Programming


Shell program is a series of Linux commands. A shell script is just like a batch file in MS-DOS but has more power
than the MS-DOS batch file. A shell script can take input from the user, file and output them on screen. Useful to
create commands that can save us lots of time and automate some tasks of day-to-day life.

Variables:
A variable is an entity that may change its value. In a program, the results of the processing statement are
stored in the computer’s memory. To make use of these values or to retrieve them we give names to these
memory locations. These names are called variables. Variables are used for storing data.
In Linux there are two types of variables they are:
1. System Variables: Created and maintained by Linux itself. These types of variables are defined in Captial
Letters. Some of the important system variables are :

System Meaning Command and output


Variable
COLUMNS No. of columns for our
screen

HOME Our home directory

LINES No. of columns for our


screen

LOGNAME Out logging name

OSTYPE Operating system type

© UNITAR International University 10 Prepared by: Shaheeda Begum


PATH Path setting

PWD Current working


directory

SHELL Shell name

USERNAME User name who is


currently logged in to
this PC

2. User Defined Variables (UDV)


Created and maintained by the user. This type of variable is defined in lower LETTERS.

How do define User defined variables (UDV)?


To define UDV use the following syntax
Syntax:
variablename=value

Example
Id=101

Rules for Naming variable names (Both UDV and System Variable)

1. Variable names must begin with an Alphanumeric character or underscore character (_), followed
by one or more Alphanumeric characters.
2. Don't put spaces on either side of the equal sign when assigning value to a variable.
3. Variables are case-sensitive, just like the filename in Linux.
4. You can define a NULL variable as follows (NULL variable is a variable which has no value at the time
of definition)
5. Do not use “?etc” to name your variable names

How to print or access the value of UDV (User defined variables)


To print or access UDV use the following syntax

Syntax:
$variable name
Example: Define variable x with value 5 and print it on the screen.

© UNITAR International University 11 Prepared by: Shaheeda Begum


Types of shall Operators:

• Arthematic Operators
• Relational Operators
• Boolean Operators
• String Operators
• File Test Operators

Arithematical Operators:

Operator Description Example


+ (Addition) Adds values on either side `expr $a + $b `
of the operator
-(Subtraction) Subtract right-hand `expr $a - $b`
operand with left-hand
operand
*(Multiplication) Multiplies values on either ‘expr $a \* $b`
side of the operand
/(division) Divide left-hand operand `expr $b / $a`
with right-hand operand
%(Modulus) Divide the left-hand `expr $b % $a`
operand with the right-
hand operand and return
the remainder
=(Assignment) Assign the right operand a=$b would assign value
to the left operand b to a
==(Equality) Compares two numbers, if [$a==$b]
both are the same return
true
!=[Not Equality] Compares two numbers if [$a !=$b]
both are different then
return true

Math Operation:

To print the math operation use expr

Syntax:
expr operand1 operator operand2

Example: How to run the shell scrip

Step1: To write shell script you can use in of the Linux's text editor such as vi or vim or nano editors

© UNITAR International University 12 Prepared by: Shaheeda Begum


Syntax:
Vi/vim/nano <filename>

To quit from the file esc :wq

Step2: To run a shell scrip


Sh <filename>

© UNITAR International University 13 Prepared by: Shaheeda Begum


Parameters

A parameter is an entity that stores values. It can be a name, number or one of the special characters.
A parameter is set if it has been assigned a value.
Syntax:
Name=[value]

If a value is not given, the variable is assigned the null string.

Types of parameters:

1. Positional parameters
Position parameters can be used when the input size is fixed and the order of the arguments in the input
is known.

2. Special parameters (Command line arguments)


Command line arguments are an important part of writing scripts Command line arguments define the
expected input into a shell script.
Several special variables exist to help manage command-line arguments to a script.

$# Represents the total number of arguments

$0 Represents the name of the script as invoked

$1,$2,$3,$4..$9 The first 9 command-line argument

$* All command line argument


$* is equivalent to “$1c$2..” ( It expands to a single word with the value
of each parameter separated by the first character of the IFS special
variable
Where c is the first character of the value of the IFS variable. If iFS is
unset, the parameters are separated by spaces.

$@ All command line argument


$@ is equivalent to “$1” ”$2” $3”
When there are no positional parameter “$@” and $@ expand to
nothing.

Condition Statements and Loops

The computer carries out the instruction in sequential order starting from the first statement to the last
statement. This is the normal flow of control, from top to bottom. It possesses decision-making capabilities and
supports statements and decision-making statements. It uses logical expression. It controls the order of
execution and changes the control flow in a program.

© UNITAR International University 14 Prepared by: Shaheeda Begum


Shall script suppots the following control structure:

1. If statement
2. Case statement

If… else…fi

Syntax:
If [condition] then
Statements
Else
Statements
fi

Output

© UNITAR International University 15 Prepared by: Shaheeda Begum


Multilevel if-then else

Syntax:

If [condition1] then
Statements
Elif [ condition2]
Statements
Elif [condition3 ]
Statements
Fi

Case Statement

The case statement is a good alternative to the Multilevel if-then-else-fi statement. It enables you to match
several values against one variable. Its easier to read and write

Syntax:
case $variable-name in pattern1)
statements;;
pattern2) statements;;

pattern N) statements;;
*) statements;;
esac

© UNITAR International University 16 Prepared by: Shaheeda Begum


Loops:
A computer can repeat particular instructions again and again until a particular condition is satisfies. A group
of instructions that is executed repeatedly is called a loop.

Shell script support the following loops:


1. For loop
2. While loop
3. Until loop

1) for loop

Syntax:

for { variable name } in {list}


do
Statements
done

2) while loop

Syntax:
While [condition]
do
Statements
Done

3) until loop
syntax
until [condition]
do
statements
done

Processes
▪ A system call is an interface between your program and the kernel. The Linux kernel's job is to
provide a variety of services to application programs and this is done using the provision of
system calls.

Understanding Processes
▪ The fundamental building block of each program is the process. A process is the name given to a
program when it is loaded “for” the purpose of execution on the operating system.

▪ To view a list of current processes in the system for a user, you may use the ps command.

© UNITAR International University 17 Prepared by: Shaheeda Begum


▪ To view the complete list, you can adapt it to ps au

▪ You will see plenty of columns as output.


▪ User: The owner of that process
▪ PID: The integer identifier
▪ CPU: Percent utilization of CPU
▪ MEM: Percent utilization of Memory space
▪ VSZ: Virtual Memory Size
▪ RSS: Non-swapped physical memory size
▪ TTY: Controlling Terminal
▪ STAT: The process states (D) Uninterruptible sleep (R) Running or ready (S) Interruptible sleep (T)
Stopped (Z) Zombie (<) High Priority (N) Low Priority (s) Session leader, i.e., has child processes (l)
multi-threaded (+) foreground
▪ START: When a process has started
▪ TIME: Time running since
▪ COMMAND: The program/command used in this process

▪ The basic attribute of a process is its ID (PID), and its Parent ID (PPID). The system calls that can find the
process ID, and the Parent Process ID is the getpid() and getppid() calls respectively.
▪ To use both of them, you will be required to include the sys/types.h and unistd.h C libraries.
▪ You can see the hierarchy of processes using pstree command

© UNITAR International University 18 Prepared by: Shaheeda Begum


1.

output

© UNITAR International University 19 Prepared by: Shaheeda Begum


2.

Output:

3.

Output:

© UNITAR International University 20 Prepared by: Shaheeda Begum


4.

Output:

5.

© UNITAR International University 21 Prepared by: Shaheeda Begum


Output:

6.

© UNITAR International University 22 Prepared by: Shaheeda Begum


Output:

7.

© UNITAR International University 23 Prepared by: Shaheeda Begum


Output:

- end of content –

© UNITAR International University 24 Prepared by: Shaheeda Begum

You might also like