Basics of Complicated Concept Programming Logic-V06
Basics of Complicated Concept Programming Logic-V06
(Programming logic)
“
TinyContent – V06
Naisit Publisher
© 2021
Contents
Chapter 1 ...........................................................................................................................................................................10
Chapter 2 ...........................................................................................................................................................................21
Chapter 3 ...........................................................................................................................................................................33
Chapter 4 ...........................................................................................................................................................................47
Chapter 5 ...........................................................................................................................................................................59
Chapter 6 ...........................................................................................................................................................................73
Chapter 7 ...........................................................................................................................................................................87
Chapter 8 .........................................................................................................................................................................102
Chapter 9 .........................................................................................................................................................................118
Chapter 10 .......................................................................................................................................................................134
Chapter 11 .......................................................................................................................................................................144
Chapter 12 .......................................................................................................................................................................162
Chapter 13 .......................................................................................................................................................................186
Decision Control Structure: Truth Tables & Conditional Statements .................................................................................. 186
What is Truth Table? ........................................................................................................................................................... 186
What is a Boolean value? .................................................................................................................................................... 187
What is a Boolean Expression? ............................................................................................................................................ 187
Types Of Conditional Statements And Their Syntax ............................................................................................................ 189
What is an If statement? ..................................................................................................................................................... 189
What is the Switch statement? ........................................................................................................................................... 191
Conditions ........................................................................................................................................................................... 194
Bash String Conditions......................................................................................................................................................... 194
Bash Number Conditions ..................................................................................................................................................... 195
Bash File Conditions ............................................................................................................................................................ 196
What are conditional statements and logical operators? ................................................................................................... 197
A simple example of conditional statements and logical operators ................................................................................... 198
What are the arithmetic operators? ................................................................................................................................... 198
Why do you need arithmetic operators? ............................................................................................................................ 198
Application of Conditional and Nested Conditional Statements ......................................................................................... 200
Final Thoughts ..................................................................................................................................................................... 202
Food for Thought................................................................................................................................................................. 203
References........................................................................................................................................................................... 204
Chapter 14 .......................................................................................................................................................................205
Chapter 15 .......................................................................................................................................................................227
Chapter 16 .......................................................................................................................................................................246
Chapter 17 .......................................................................................................................................................................262
Chapter 18 .......................................................................................................................................................................275
Chapter 19 .......................................................................................................................................................................292
Chapter 20 .......................................................................................................................................................................305
Chapter 1
“
A world without computers would be unimaginable in today's times. We can't
thank enough the geniuses who invented the computer and modified and
perfected it through different epochs in history. The legacy they have left behind
History of Computer
machines over the years, starting from the wheel to vehicles to computing marvels
such as 'Computers.' Though one uses the computer for various purposes today, it
1880 US Census results led to the invention of computers. However, the credit for
sowing the magnificent invention seeds goes to the English mathematician, Charles
Babbage (1822).
10
The Difference Engine (Serial no. 2), which was invented by Charles Babbage. Located currently in the Computer History
Museum in Mountain View, Silicon Valley, California. Image source: Flickr.com
In the earlier days, computers were restricted to specific operations. It took over
four decades for scientists to come up with the notion of a universal machine. Alan
11
Turing presented the first such machine in 1936, and the modern-day computers
result from his concepts.
12
efforts of Dr. John V Atanasoff and Clifford Berry. Appropriately, the machine
was named ABC (Atanasoff Berry Computer). Other inventors like Howard Aiken
developed devices capable of performing calculations involving large numbers.
13
first computer for commercial use, the Universal Automatic Computer (UNIVAC
1). The same year saw IBM manufacturing its 650 and 700-series computers. This
generation also saw the introduction of various computing programs like COBOL
(Common Business Oriented Language), FORTRAN (Formula Translation), and
the integrated circuit's introduction, also known as 'the chip.'
a) IBM 1620
b) IBM 7094
c) CDC 1604
d) CDC 3600
e) UNIVAC 1108
The chip's invention paved the way for the third generation of computers (1963 to
1980), leading to a revolution in the computer manufacturing industry. In 1969,
Bell Labs invented the first operating system, UNIX. The Dynamic Access
Memory chip (DRAM) was born in 1970 when Intel unveiled the world's first
DRAM chip, Intel 1103. It was followed by many path-breaking inventions like
the floppy disk, Ethernet, and other hardware.
This period between 1963 and 1980 was a golden period with the incorporation of
companies such as Microsoft in 1975 by Paul Allen and Bill Gates, and Apple
Computers by Steve Jobs and Steve Wozniak.
Though IBM started manufacturing mainframe computers in 1952, the demand for
these massive machines peaked during the 1960s and 1970s. Mainframe computers
14
are often used as servers. One can link numerous individual personal computers to
these servers and form a network.
The period from 1971 to 1980 saw the invention of the following computers.
a) DEC 10
b) STAR 1000
c) PDP 11
d) CRAY – 1
e) CRAY – X – MP
The last two names were the first supercomputers to see the light of day.
15
Apple-1, the first computer designed by Steve Jobs and Steve Wozniak in the 1970s
The world's first personal computer, Acorn, was released in 1981 by IBM. It
worked on Microsoft's MS-DOS operating system with an Intel chip, an optional
colour monitor, and two floppy disks.
Apple introduced the first PC with a GUI in 1983. It was named Lisa but
eventually evolved into the Macintosh. The same year witnessed the invention of
the first portable computer Gavilan SC, which was marketed as a laptop.
March 15, 1985, was a red-letter day in the history of computers because of the
registration of the first dot-com domain name before the birth of the World Wide
Web and the formal introduction of the internet. Around the same time in 1985,
Microsoft announced Windows.
16
1996 witnessed the launch of the Google search engine by Sergey Brin and Larry
Page. Wi-Fi became a reality in 1999 as users started to connect to the internet
without wires.
The 21st century had an auspicious beginning, which started by introducing the
MacOS by Apple and the rolling out of Windows XP by Microsoft in 2001.
The world's first 64-bit processor, AMD Athlon 64, saw the light of day in 2003.
a) Desktop PC
b) Laptop
c) Notebook
d) Ultrabook
e) Chromebook
f) MacBook
17
A modern-day laptop
If someone had predicted that you would be able to carry the computer in your
pocket at the time of the ENIAC installation, the world would have termed them
insane. However, every one of us does hold a computer in our palms and accesses
the internet using a device better known as a smartphone.
18
and the internet have opened up several vistas of communication. Thus, we can say
that the computer has travelled a long way since the days of Charles Babbage. It
has brought the world closer. At this developmental rate, we do not know what the
future holds for us; computers have made radical changes to the world we live in.
Final Words
The subsequent events in the history of computers are too recent to merit a mention
here. Today, we carry a piece of computer in our hands in the form of smartphones
and other devices that we use daily. Since the inception of the first 'computer,' we
have travelled quite a long way, but the inventors' legacy still lives on. We have
traced the path that computers have travelled since 1820. Now, we are indeed at a
crossroads where the computer defines the way we go forward.
19
References
1. Contributor, K. (2020). History of Computers: A Brief Timeline. livescience.com.
Retrieved August 23, 2020, from https://www.livescience.com/20718-computer-
history.html.
3. Contributor, S.H., The History of Computer Technology, Medium.com (March 07, 2019)
Retrieved August 24, 2020, from https://medium.com/newtown-partners/the-history-of-
computer-technology-cf87154a7bc1
20
Chapter 2
“
Computer programming languages instruct the computers what to do, but the
way they introduce varies from language to language. This chapter looks
through the complex but exciting history of computer programming and
discusses different programming languages.
21
In 1843, Ada published for the first time, a sequence of steps to perform
calculations, using the differential engine designed by Charles Babbage. She used
these notes to calculate Bernoulli numbers, a mathematical series. These notes
constituted the first-ever computer program.
Jon Von Neumann, working at the Institute of Advanced Study, in 1945, developed
two significant concepts that would go on to shape computer programming.
22
Konrad Zuse, a German scientist, used concepts from Jon Von Neumann's work in
his machines and the Plankalkul programming language. This language was the
first high-level programming language and started the early era of programming.
1949 witnessed the birth of the language Short Code, the first computer language
for electronic devices. Short Code was primitive because the programmer had to
change the statements into 0's and 1's manually. Nevertheless, it was the initial step
towards the development of modern computer languages.
23
In 1951, Grace Hopper devised the first compiler, A-0. The compiler converted
language statements into 0's and 1's automatically for the computer to understand
better. With the programmer no longer having to do anything manually, the speed
of programming increased significantly.
John Backus and other scientists at IBM designed the first high-level programming
language, FORTRAN, on October 15, 1956. FORTRAN is derived from the words
- FORmula TRANslating system. This program used the statements, 'IF,' 'DO,' and
'GOTO.' It might appear to be restrictive by today's standards, but it was a path-
breaking for its time.
24
Pascal's development marked the end of the first era of computer programming and
signalled the second era's birth with the development of languages like C and C++.
Niklaus Wirth developed Pascal in 1968 as a necessity for a useful teaching tool. It
combined the best features of other languages like Algol, FORTRAN, and COBOL
by refining their irregularities and cleaning them.
This era of computer programming paved the way for developing different
programming languages to cater to many requirements. It also began when
computers were starting to be accepted globally.
• An extension of C – C++
C++, an extension of C language, is used in the in-game engines and
software like Adobe Photoshop. Developed by Bjarne Stroustrup in 1983,
C++ is still the preferred language for many packaged software.
25
The same year saw the development of a unique language used for writing
software for iOS and macOS. Named as Objective-C, Brad Cox and Tom
Love created it.
• JavaScript
JavaScript has a reputation for being created in the shortest time - just ten
days by Brendan Eich in 1995. It is universally used for enhancing web
browser applications.
26
Fourth Generation Languages have statements that are similar to human languages.
A single command that the programmer enters can allow it to perform multiple
everyday operations. These are easier to use for users than first-generation
(machine languages), second-generation (assembly languages), and third-
generation (older high-level) languages. They include SQL, Ruby, Python, Pel, and
MatLab.
27
These languages have visual tools that help programmers develop the program.
Some examples are OPS5, Mercury, and Prolog.
28
Types of Development
• Front End Development A front end developer is in charge of the user side of
the applications. They code webpages, software, games, and application that
users see. Examples of front end coding languages are HTML, CSS, Javascript,
etc.
• Back End Development It is also called server-side programming. The back
end developers take care of the things that happen behind the scenes. Some
back-end programming languages include Python, Java, Ruby, etc.
29
• Full-stack development This type of development takes care of both the client-
side (front-end) and server-side (back-end) portions of developing a web
application.
Types of Developers
• Web Developer A web developer takes web designs from clients or design teams and
transforms it into a website by writing code lines. They use different languages to achieve
this, like Python or HTML.
• Desktop Developer Programmers writing code for applications running natively on
operating systems like Windows, macOS, and Linux are called desktop developers. These
applications don’t need an internet connection to work.
• Mobile Developer They are software developers who specialize in mobile technology. They
build applications for Android, iOS, and other mobile platforms. They choose the language
for coding according to their chosen medium (Android – Java, iOS – Objective C, etc.).
Final Words
30
Answer: C++ sits close to the hardware, can manipulate the resources
efficiently, and is fast. Hence, it finds its uses in Games, GUI based
applications (Adobe systems, Win Amp Media Player, etc.), Database
software (MySQL), operating systems (Apple OS, windows), Browsers,
among other applications.
31
References
32
Chapter 3
Computer Basics
“
Learning The Key Terms Associated With Computers And Their Functioning
Computers operate on instructions and binary codes. The data fed to the computing
device is processed and then reflected or shown on the output device. The
foundation of computing (or computers) is based on three necessary steps:
Input: The term input means putting something 'in.' Input in computers refers to
the command or signal fed to the device. Several devices are used to provide Input
(data) to the computer, known as 'Input Devices.'
33
Process: The execution of the data inserted by the user is known as the 'process' in
computing. The processing takes place within the CPU (Central Processing Unit)
and is invisible to the human eye.
34
35
• Input Unit: As discussed above, the input unit comprises input devices like
keyboards and mouse. These devices are used to feed instructions to the
computer.
• Output Unit: It consists of devices like the monitor, printer, and visual
display unit. These devices provide information to the user after the raw data
has been processed.
• Control Unit: The control unit is responsible for all the functions of the
computer. It keeps all devices or parts of the computer in interaction with
one another.
• Arithmetic Logic Unit: The Arithmetic Logic Unit (ALU) is known as the
computer's brain and regulates all arithmetic and logical operations.
• Memory: Yet another vital component of the computer system is memory.
Memory stores all data entered by the user until the data gets processed to
information. There are two types of memory– primary
memory and secondary memory. Primary memory is the main memory of
the computer and is a part of the CPU. Secondary memory refers to
additional memory that is used to store files permanently or in a portable
format. Some secondary memory devices are CDs, DVDs, floppy disks, hard
drives, and pen drives.
• Central Processing Unit: CPU (Central Processing Unit), also known as the
central or main processor, is a crucial element of the computer system. It
comprises the Control Unit (CU), the Arithmetic Logic Unit (ALU), and the
memory. CPUs are responsible for prompt computer actions – be it the quick
delivery of complex calculations or animations, video and audio merging,
etc.
36
Types Of Devices
The devices that keep the computer system working are of different types and have
different functions. The following is a list of some primary input and output
devices along with their descriptions:
INPUT DEVICES
MOUSE The input device mouse is plugged into the CPU and functions as a
direction indicator and operator that enables a user to select or deselect a
file. It comes with two buttons (left and right) and a scroll wheel.
KEYBOARD Designed in-line with the olden typewriters, this input device comes with
buttons (or keys) that contain all alphabetical letters, numbers from 0 to 9,
and an array of other special characters and operations.
MICROPHONE The microphone is not an essential input device, but it can capture audio
signals by converting sound waves into electrical signals.
SCANNER Scanners or image scanners can scan hard copies of documents or
photographs and convert them to soft copies stored and viewed on a
computer.
WEBCAM Webcams came into the picture much later and can be used for clicking
pictures, video conferencing, or recording.
OUTPUT DEVICES
MONITOR The monitor is one of the computer system's main components and the best
example of an output device. It is a television-like device with a screen.
Although monitors these days come in LED or LCD variants, the first
monitors were the boxed-shaped CRT ones. Monitors display every action
performed by the user on the computer and show the final output after
processing the CPU data.
PRINTER The peripheral device Printer is used to print documents or pictures stored
on the computer unto paper, thus converting soft copies of files into hard
37
copies. Printers are of different types, such as inkjet printer, laser printer,
thermal printer, and today we have 3D printers. Printers could only perform
black and white printing when they first came out, but over time, they have
evolved into these powerful machines (such as 3D printers) that we know
of today.
SPEAKER Speakers come with computers and work as loudspeakers that convert
audio signals into audible loud sounds that can be heard by the human ear.
38
and earphones, etc.) provide instructions to the software and display its
execution results.
• Types of Software:
1. System software includes software designed to manage the computer,
like the operating system, DOS (disk operating system), or file
management utility. System software acts as a platform for developers
to design applications. Examples of system software are OS, antivirus
programs, disk formatting software, etc.
2. Application software: They are also called end-user programs and lie
on top of the system software. They help the user perform tasks on the
system like surfing the web, graphic designing, playing games, doing
calculations, etc.
3. Utility software: They are used for analyzing and maintaining the
computer. They focus on the working of the OS and enable smooth
functioning of the system. Sometimes, they are included in the OS
package. Some examples are file manager, antivirus, disk
compression tool, etc.
4. Free distribution software: This software is available to the user
without any cost. They can simply download the free distribution
software from the internet and start using it. Unlike open-source
software, users cannot modify, share, or study free distribution
software. Some examples are: Adobe PDF, yahoo messenger, Google
Talk
5. Commercial software: Commercial or shareware software are
available for download free of cost. However, they come with an
39
inbuilt time limit. (30 days to 2 months). After the time-limit, the
software gets deactivated automatically, and the user needs to buy it to
continue using it. Examples are Adobe acrobat, PHP Debugger,
Winzip, Getright, etc.
• Motherboard: A motherboard or mainboard is a circuit board that facilitates
the power distribution and communication between the CPU, RAM, and
other computer peripherals. It acts as the backbone for connectivity within
the computer and contains important computing components such as the
CPU, RAM, power supply, sound card, graphics card, etc.
• RAM & ROM: RAM and ROM are two integral parts of a computer
system's primary memory. RAM refers to the Random Access Memory, and
ROM stands for Read-Only Memory.
40
41
Hardware Software
These are physical devices connected to the These are programming codes installed in the
computer system. computer's hard drive.
These are tangible devices. These are intangible and exist in the form of
codes.
Hardware is integral to a computer's smooth The software adds to the basic functioning of a
functioning. computer system.
Examples - Monitor, mouse, and keyboard. Examples - operating systems, internet
browsers, or applications are examples of
software.
Final Words
Ever since the invention of computers in the 1880s, there has been an exponential
growth and evolution of computers. From desktops to laptops, CRT to LED
monitors, computers are becoming compact, affordable, power-packed, and
efficient. Understanding computers' basic concepts are the first step towards diving
into the vast ocean of technological advancements.
42
Across Down
6. Input device closely connected with the 4. Output devices producing sound
world of music
43
Do You Know?:
➢ Did you know that the world's first mouse was wooden? Doug Engelbart
invented it in around 1964.
➢ One striking similarity between tech giants HP, Microsoft, and Apple is
that they were all started in a garage.
➢ Computers weren't always the way they are now. The earliest computers
were created in the 1940s and occupied an entire room and lots of
electricity.
➢ Don't they tell us gadgets are addictive? We do blink only seven times
every minute while using a computer; the number is 20 otherwise.
➢ When first invented, keywords had letters arranged in alphabetical order.
The 'Q' 'W' 'E' 'R' 'T' 'Y' system came in later because human typing speed
was faster than the computer's ability to process data.
44
References
45
46
Chapter 4
“
Human evolution finds problem-solving at its core. Problem-solving traces back its roots into
the earlier twentieth-century Germany, with the work of Gestaltists. It is the seed for all the
latest inventions, cultural growth and marks the foundation of market-based economies. This
chapter deals with the history of problem-solving, which has been one of the foundations for
the evolution of humankind.
47
It means focussing on the problem, and not merely its symptoms. Flowcharts and
cause and effect diagrams can help in diagnosing the root causes of the problem.
There are a series of considerations that skilled problem solvers take into account
to choose the best alternative. These include:
• The alternative must solve the problem efficiently without creating other
unanticipated issues.
• The alternative must be acceptable to all the concerned individuals.
• The likelihood of the implementation must be high.
• The alternative must fit in the organizational constraints.
4. Implementing and following up on the proposed solution
48
problem-solving approach is, "Keep trying until you succeed." It forms the basis of
the trial and error problem-solving method. Other problem-solving types are
summed up in the table below.
49
50
51
• What is Computation?
• Theory of Computation
"For a given number ‘n’ (a positive integer), find its nontrivial prime factor."
52
53
• Creativity
• Collaboration
• Communication
• Critical Thinking
The fifth element in the four Cs can be the algorithmic and logical ability of
problem-solving – computational thinking, as computational thinking finds
54
• Abacus
The abacus is believed to have originated about 5,000 years ago in Babylon.
Thus, it predates the invention of the alphabet and glass making! Before the
counting machines were invented, people made marks in the muds, used
their fingers, or used stones for counting. The earliest abaci included shallow
trays that were filled with dust (a layer of fine sand).
The first analog computer can be traced back to 1873, a particular purpose
machine made by William Thomson. He was also called Lord Kelvin. The
55
Q. There are two trains 150 miles apart and are travelling toward each other
along the same track. Assuming that the first train's speed is 60 miles per
hour, the second train rushes along at 90 miles per hour. There is a fly that is
hovering just above the nose of the first train. It flies from the first train to the
second train, turns around immediately, it then flies back to the first train, and
turns around again. It repeats the same activity and keeps on flying back and
forth between the two trains. It does it until both the trains collide. Assuming
that the fly's speed is 120 miles per hour, how far will it travel? [Source:
Two Trains and a Fly]
A. What's your first thought after reading this problem? Do you feel like
approaching this problem with the infinite series method? Well, you're not
alone! That's what Mr. Neumann thought. However, there's a simple solution
to this:
Concentrate on the trains, and forget about the fly for a second. The speed of
the first train is at 60 miles/hour, and the second train is going 90 miles/hour,
56
so they are approaching each other at (60 + 90) miles/hour = 150 miles/hour.
So, we have the rate at which the trains are closing in on each other and the
distance between them (150 miles), now it has merely become a speed-
distance-time problem, and we can calculate the time as:
Now, we know that the time spent by the fly will be equal to the time spent by
trains travelling. It was given that the fly moves at 120 miles/hour; therefore,
in the one hour the trains take to collide, the fly will go 120 miles.
From this question, we learn how it's crucial to approach a problem the right
way. Had we used a mathematic approach for this, it would have taken us
much longer to solve it.
Final Words
The key to solving a problem is reaching a goal state and overcoming the
circumstances that stand in the way. The most powerful problem-solving machine
is the human mind, which is solving problems every second! Problem-solving is
the epicentre of the computational world, which forms the foundation of our
advancement as a whole, and pushes us to generate innovation-driven ideas that
can be implemented for solving some of the most crucial real-world problems.
57
References
58
Chapter 5
“
Solving any problem is always fun if you adopt the right approach. Computers
can help in solving problems fast, but you need to program them accordingly. In
this chapter, we discuss some interesting methods, tools, and tips to solve
computational problems.
Introduction
One of the principal applications of a computer is to solve problems that are not
humanly practical. The reason is that the computer can perform permutations and
combinations better and faster than humans. A computer also takes a logical
approach when solving a problem. This chapter discusses how to solve a
computational problem in the right and efficient way.
59
60
61
Each of these four cornerstones has its significance. One should apply all these
four techniques to arrive at the best possible solution.
62
As you break down the task into smaller activities, it becomes easy for you to plan
the vacation.
Adopting the five-step method to solve computational problems is the best way to
approach any problem on hand.
63
64
• Pseudocode
Pseudocode is similar to the flowchart, as it expresses a computational process.
In simple terms, pseudocode is a code that a machine cannot understand. On
65
the other hand, humans can understand it. It allows you to bring in the element
of creativity when solving problems.
• Flowcharts
A flowchart is the step-by-step dissection of the problem. It helps you to write
down the computing process. A flowchart consists of different kinds of steps
like,
a) Instruction Steps – They represent the actions you need to perform. When
preparing a flowchart, you write the instruction steps inside a rectangle.
b) Decision Steps – Such steps can have more than one answer. Depending on
the answer, you proceed in a specific direction. You write decision steps
inside a diamond-shaped figure.
• Mathematical Models
Mathematical models help to understand the problem and its characteristics. It
enables you to reason and arrives at a logical conclusion. Creating a
mathematical model is crucial for solving computational problems. The
advantage is that mathematically described models are compatible with
computers using mathematical techniques like graph theories, algebra, etc. A
66
• Operators
Just as you have different mathematical signs to indicate the steps to solve
mathematical problems, computers have operators to verify elements' validity.
These operators do not express numbers but True/False values. The computer
uses the True/False values to proceed ahead sequentially. The direction of the
problem-solving process changes with every True/False value.
• Logic
Solving any problem is one aspect. However, one should also be able to
explain the procedure used to arrive at the respective solution. It is done by
applying logic, which is critical because the answer should be the same every
time you input the same data. As a corollary, a different input should provide a
different yet consistent solution to the problem.
Those were the theoretical aspects which are the fundamental steps that one should
use when solving problems. Now, here are specific tips that can help you approach
any situation and go about solving it with confidence and effectiveness, thereby
improving the chances of finding a logical solution.
67
68
• Find Analogies
Every problem would have some precedents. Logical thinking of the problem
can help you find analogies, thereby making it easy for you to understand the
issue on hand.
As you dissect the problem and find analogies, you may find the need for
experimentation. While some analogies might lead you to the right solution,
some could be confusing. Unless you experiment, you will never know.
Experimentation also improves your perception skills.
69
Final Words
Problem-solving is fun, provided you adopt the right approach. Every problem has
a logical solution. If you plan well and approach the problem step by step, it should
be easy to find a solution. You can use the fundamental techniques, tools, and tips
discussed in this chapter to formulate a practical problem-solving approach. It will
enhance your chances of arriving at the right solution every time you embark on a
problem.
Given below is a small program in C language that would help the computer
to understand and solve the problem. As an example, the number 29 has
been used. You can try out with any number and arrive at the solution
accordingly.
70
71
References
72
Chapter 6
“
Digital systems are passive by themselves and require coded instructions for
delivering results. Today's digital era is driven by the mathematical model and
is backed by algorithms for providing the outcome, whether it is launching a
rocket or displaying movie recommendations.
73
Introduction To Algorithms
An algorithm consists of a set of rules and steps that should be followed during
problem-solving. An algorithm is provided with some inputs for processing, which
gives out desired outputs after following a set of predefined steps. In programming,
a concise description of such executable instructions is known as pseudocode. An
optimal algorithm is one that executes in minimum time using minimum resources
and possesses the following characteristics.
• Input: Zero or more inputs supplied externally
• Output: One or more structured, desired outcomes
• Correctness: Each step in an algorithm should produce relevant results
• Definiteness: Each step should be well-defined and unambiguous
• Finiteness: The algorithm should execute in a well-defined number of steps
74
Searching and sorting are two essential functions that play an indispensable role in
many programs.
Search algorithms involve looking up databases for the requested items. They
search for an item x in an array of elements A[0….n] by cross-checking items in
position 0 to n, one by one. The two main search algorithms are.
• Bubble sort: The first two elements are compared and swapped for
ordering. This interchanging is iterated until complete sorting.
• Insertion sort: The second element is compared, and items are
interchanged, followed by the third element, and so on.
• Merge sort: It is based on the 'divide and conquer' algorithm, and is
discussed in the subsequent section.
• Selection sort: It maintains two sub-arrays and repeatedly finds the
smallest element in an unsorted array and sorts it.
75
Types Of Algorithms
Each algorithm differs from another in the flow of control, repetition, speed, and
efficiency. They can be broadly classified into six, as described below.
1. Recursive Algorithm
A Recursive algorithm takes smaller inputs and repeats its execution until a
solution is found. These algorithms are mainly used for the Tower of Hanoi and
DFG graph-related solution searches. These algorithms are computation-
intensive and need more memory than iterative algorithms but are more
straightforward and represent a natural way of thinking.
An example code of the recursive algorithm is given below.
factorial (number)
if number is 0:
return 1
otherwise
return (number * factorial (number-1) )
2. Greedy Algorithm
The Greedy algorithm is an intuitive algorithm that finds the optimal solution for
each step as it considers an overall optimal solution for the entire problem. Such
optimization problem-solving algorithms are commonly used in Huffman
encoding and also in Dijkstra's algorithm. The Greedy algorithm works by
taking into account all data associated with a specific problem and then sets
76
rules for each element added in each step while solving the problem. The
algorithm generally comprises of five components:
77
The below example describes a sequential search using a brute force algorithm.
78
Fibonacci(N)=0 (N=0)
Fibonacci(N)=0 (N=1)
Fibonacci(N)=Fibonacci(N-1)+Fibonacci(N-2) (N>1)
6. Backtracking Algorithm
Backtracking is a systematic approach in which the code solves problems
recursively by building solutions incrementally and deleting solutions that do
not satisfy the given constraints. In other words, the algorithm tries to solve a
sub-problem, and if it fails, then the final solution will be truncated, and the
algorithm starts again to find another solution.
N-Queens and Sudoku are typical applications of the Backtracking algorithm.
The N-Queen problem is based on the fact that there are N queens on the
chessboard, and once arranged, none of the queens attack the other. The
pseudocode for the N-Queens problem solution using a backtracking algorithm
is given below.
CheckValid()
If queen at left of current column, return false
If queen at upper-left diagonal of current column, return false
79
80
• Problem Analysis
This step involves connecting the endpoints. The developers have data,
rules, and interconnection between data. They need to come up with facts
and also include changes.
81
• Refinement
Also called step-wise refinement, developers will include even minor details
if required in this step. These detailed descriptions will be added only after
high-level algorithm development.
• Review
The final review ensures that the problem has been solved, and the solutions
are the most optimal solutions possible. Moreover, simplification, if
possible, will be done in this step.
Analysis of an algorithm gives insights into the complexities of the code, time, and
space. It also helps programmers to discover the characteristics of the algorithm
and its applications. The efficiency of algorithms is measured in terms of the
following notations.
• Omega (Ω) Notation
Omega notation represents a formal way of expressing the lower bound of
an algorithm's execution time and is a measure of base-case time
complexity. For instance, it takes 10 seconds to sort 1000 numbers; in
omega notation, these numbers cannot be sorted in less than 10 seconds.
• Theta (Θ) Notation
Theta notation defines asymptotic behaviour and represents lower and upper
bounds and represents an average running time of the algorithm. To
exemplify, if one algorithm takes 7 seconds to sort 1000 numbers and
82
83
Final Words
It is evident that algorithms form the foundation for flawless operation of digital
systems, and the most impressive services are built on top of well-defined
algorithms. Which algorithm to use for each project is up to the developer. New
forms of dynamic algorithms have been increasing to cope with the changing
digital world, such as that for ANN Artificial Neural Network and other data
analytic techniques.
84
References
85
https://www.hackerearth.com/practice/algorithms/dynamic-
programming/introduction-to-dynamic-programming-1/tutorial/
8. GeeksforGeeks. (2020). Backtracking Algorithms.
https://www.geeksforgeeks.org. Retrieved August 28, 2020, from
https://www.geeksforgeeks.org/backtracking-algorithms/
9. Edwards, Stephen. (2012). Problem Solving and Algorithms.
http://sofia.cs.vt.edu/. Retrieved August 28, 2020, from
http://sofia.cs.vt.edu/cs1114-ebooklet/chapter4.html
10.Obosi, Philip. (2020). A Gentle Introduction to Algorithms and Data
Structures. https://scotch.io/. Retrieved August 28, 2020, from
https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/a-
gentle-introduction-to-algorithms-and-data-structures
11.Zaveri, Meet. (2018). An intro to Algorithms: Searching and Sorting
algorithms. https://codeburst.io/. Retrieved August 28, 2020, from
https://codeburst.io/algorithms-i-searching-and-sorting-algorithms-
56497dbaef20
12.Panchal, Sumeet. (2019). What is Runtime Analysis of Algorithms.
https://medium.com/. Retrieved August 28, 2020, from
https://medium.com/@sumeetpanchal.21/what-is-runtime-analysis-of-
algorithms-cf321bd65636
86
Chapter 7
Flow Charts
“
Algorithms and programming languages work hand in hand to execute
programs in digital systems. But it is vital to make such instructions
documentable and understandable among non-technical staff too. A flowchart
plays a crucial role in achieving it.
87
Introduction To Flowcharts
88
box (or activity box), which represents a processing step, and a diamond box,
which means decisions.
Flowcharts are used for representing computer programs, and modern diagrams
such as UML and Drakon charts are all extensions of flowcharts. There are mainly
four types of flowcharts, as described below.
Flowcharts can provide a visualization of how the code is executed and users
navigate a program. The execution of the code inside a program can also be
represented using flowcharts. Like any other process, the designing of flowcharts
takes place through a series of steps, as shown below.
89
1. Define the algorithm to be visually represented and write a title for the
flowchart.
2. Decide the inputs and output for the process and identify the limitations.
3. Brainstorm the activities that will take place and take note of it.
5. After the process has been sequenced, draw shapes, and connect each step
without compromising the flow.
6. Review and modify the flowchart to ensure that the flowchart's logic and
relevance have not been compromised.
90
Shapes Of Flowchart
The following table illustrates the symbols and their associated usage in
flowcharts.
Name Symbol Function
Denotes the starting or ending of
Start or End an algorithm and contains the
word Start or End
Represents a single process or
Action or Process entire sub-process within an
extensive process
Denotes a printed report or
Document document
Denotes different decisions
Decision emerging from various points
Represents the input given by
Input or Output the user or the result generated
by the system
An indication that the flow
continues where a matching
Connector symbol has been placed
anywhere else in the flowchart
Indicates the sequence of
Flowline instructions and the flow of
control
Represents a delay during the
Delay process
An indication that one or more
Merge sub-sets merge into one step
91
In a flowchart, branching represents that the process splits based on two or more
conditions, and the control of the program will continue based on user preference.
A diamond-shaped decision box takes the user preference or changes the flow of
control based on previous results. The three main decision statements are discussed
below.
• 'If' statement
The 'If' statement is a widely used conditional statement that redirects
the flow of control in one path if the condition is 'true' and halts or skips
some steps if it is not valid.
92
If Else If Statement
Image source: javatpoint.com
• Switch statement
A switch statement or case statement is a multi-way decision-making
statement. If value equals one of the case conditions, a particular block of
instructions will be executed among various other conditions. If no
conditions are 'true,' a default set of statements will be performed.
93
94
Microsoft Visio is a powerful tool to create interactive flowcharts and modify them
at later stages if required. Visio also allows developers to store data and compare
or evaluate information before further additions to existing algorithms. It is
recommended to follow the below steps to create a flowchart in MS Visio.
2. Select the 'New Flowchart' option, and choose a shape from the list of
forms in the sidebar to create a flowchart.
3. Drag and drop the required shape from the sidebar. Whenever a user
hovers over any shape, the name and details of the shape will be
shown. The start and the end of the process can be represented with
the terminator symbol.
4. Double click on the shape and write the name for each process and
continue until all shapes have been assigned some names. Use the
connector tool for connecting all the functions in the flowchart.
95
More tools, free, open-source, and paid, are available in the market for creating
flowcharts. Here's is a list of some of the most popular ones.
• Draw.io: Draw.io is a tool that can create flowcharts and works across all
sorts of platforms. The documents can be stored either on the system or
cloud storage.
• Pencil: Pencil is a tool with many useful provisions, including linking the
flowcharts and graphs with different locations on the same document.
96
Paid tools
• Edraw Max: With Edraw Max, one can work with readily available
templates and symbols. It also allows one to work with multiple file formats.
• Visme: Visme is a tool that allows handling many visual tools, infographics,
and graphs, besides flowcharts.
Applications
The purpose of the flowchart is to convey how the process works even to non-
technical staff. Such pictorial representation is useful in engineering, physical
sciences, computer programming, and even entertainment. The below descriptions
examine the applications of flowcharts.
97
• Planning a new project: Engineers and scientists can decide the flow of
process while designing a new project and assign tasks to their
workforce.
98
Final Words
The flowchart or process flow diagram plays a prominent role when developers
start working on their projects. It is also beneficial to identify malfunctions and
make non-technical staff understand the tasks they are supposed to do. Otherwise,
algorithms and programming languages will be complicated for non-technical
employees. Many newer forms of flowcharts have been developed from time to
time. However, the symbols and structure are still more or less the basic, globally
accepted ones. The advent of technology has resulted in various automatic
flowcharting applications that read the source code and develop detailed visual
representation.
99
Fill out the cross-word using the hints provided below the puzzle. All the answers
are related to flowcharts.
Across:
1. I am rectangular while designing a flowchart. What am I?
2. You use me whenever you want to represent a decision-making step.
4. You use me to communicate ideas, and I represent a problem-solving
process.
5. I join two different geometrical boxes with the flowcharts.
Down:
1. I represent data or information available in the flowchart.
3. I am elliptical, and all flowchart begins with me. What am I?
100
References
101
Chapter 8
Pseudocode
“
Structured Language to Describe Algorithms
Do you want to know about an informal way of programming that does not need
any strict programming syntax or technology considerations? In this chapter,
we learn about pseudocode – a casual way to create a rough draft or program
outline..
Introduction to Pseudocode
Why Pseudocode?
102
What is Pseudocode
Suppose you want a program that prints even numbers from 0 to 99. The
pseudocode for the same program will look like this:
set i to 0
for each i from 0 to 99
if i is even
print i
end for loop
Note: Since there is no specific syntax for a Pseudocode, you might have a
different one in your mind.
Due to its simplistic nature, pseudocode may sound trivial to many users. They
simply need to convert the above code in simple English to the actual one. Below,
we give a translation of the pseudocode, as mentioned above in C++, Python, and
Java:
103
C++
#include <iostream>
using namespace std;
int main() {
// Printing even numbers from 0 to 99
for (int i = 1; i <= 99; i++) {
if (i % 2==0)
cout << i << endl;
}
}
Python
Java
class HelloWorld {
public static void main( String args[] ) {
// Printing even numbers from 0 to 99
for (int i = 1; i <= 99; i++) {
if (i % 2 == 0)
System.out.println( i );
}
}
}
104
Pseudocode Algorithm
Pseudocode refers to an informal The algorithm refers to the step-by-step
way to write a program. One cannot procedure for solving a problem. The
classify it as a computer program process consists of a fixed set of
because it represents the program instructions, where each instruction
algorithm in a simplistic and natural gets executed in a finite amount of
language. Since you write it in time. A typical example of an
simple English language, there is no algorithm is the steps you take to log in
strict syntax of writing a Pseudocode to your Facebook account.
like other programming languages.
Programmers use several formats for You can express algorithms in simple
writing Pseudocodes, most of which and natural language, or by using
are inspired by language structures flowcharts.
like C, FORTRAN, etc.
Example of Pseudocode for Linear Example of Algorithm for linear
Search: search :
105
1. First things first, arrange the sequence of tasks you want to complete through
the pseudocode.
2. Start writing the pseudocode by defining a statement that establishes the
primary goal.
3. You must indent the if-else, for and while loops in the pseudocode, if they are
indented in the program. While improving the readability for users, it will also
allow them to comprehend the mechanism of decision control and
implementation.
106
For Example:
if "1."
print response
"we are group 1."
if "2."
print response
"we are group 2."
107
The "structured" part in pseudocode refers to a notation used to represent the six
structured programming constructs. These are SEQUENCE, IF-THEN-ELSE, FOR,
WHILE, REPEAT-UNTIL, and CASE. You can embed any of these constructs inside
other constructs. They represent the flow of control or the logic of an algorithm.
Let's look at each one in detail:
1. SEQUENCE
A non-computer example:
Brush teeth
Smile in mirror
Wash face
Comb hair
Another example of a sequence:
108
Some Common Action Keywords which you can use to indicate input, output,
or processing operations are:
• IF
• THEN
• ELSE
• ENDIF
The general form of writing this expression is:
IF condition THEN
group 1
ELSE
group 2
ENDIF
109
Note: The "Group 2" and ELSE keyword are optional. For true condition,
"group 1" gets executed, otherwise "group 2" is executed.
ELSE
ENDIF
3. FOR
sequence
ENDFOR
It is prudent to use problem domain vocabulary in cases when loop bounds are
easy to infer.
110
4. WHILE
The WHILE construct specifies a loop which contains a condition at the top.
WHILE will indicate the beginning of the loop, and ENDWHILE marks the
ending. The general form of the WHILE construct is:
WHILE condition
sequence
ENDWHILE
The program enters the loop only if the condition is true. It performs the
"sequence" for each iteration. In the end, it again evaluates the condition and
continues the loop until the condition is true.
ENDWHILE
111
5. REPEAT-UNTIL
The REPEAT-UNTIL loop shares similarity with the WHILE loop except that
the condition test is done at the end of the loop, not at the start. It uses two
keywords: REPEAT and UNTIL. The general form of the REPEAT-UNTIL
loop is:
REPEAT
sequence
UNTIL condition
Since the condition is checked after the sequence's execution, the REPEAT-
UNTIL loop performs the series at least once. The loop keeps repeating till the
time condition remains false, and when it becomes true, it terminates.
6. CASE
• CASE
• OF
• OTHERS
• ENDCASE
CASE expression OF
112
ENDCASE
ENDCASE
7. NESTED CONSTRUCTS
You can also embed constructs within each other by using indenting in
pseudocode. The point worth noting here is that you must indent the nested
constructs from surrounding constructs.
113
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF
The IF construct nests within the REPEAT construct in the given example.
114
Integer i, j, k
Set k = 8
for(each i from 1 to 1)
for(each j from the value of i to 1)
print k+1
end for
end for
Ans: 9
Explanation:
The code uses a nested FOR loop. It declares i,j, and k variables, and the initial
value for k is 8.
2. In the inner FOR loop, j value is 1, and the condition j<=1 is correct. Hence
it prints K+1.
3. Then it increments the j value by 1; hence j=2, the condition for inner FOR
loop (2<+1) becomes false.
5. The answer is 9.
115
Final Words
In this chapter, you learned that pseudocode summarizes the program flow,
excluding the underlying details. It acts as a crucial tool for system designers who
want to make it easier for programmers to understand a software project's
requirements and align their codes accordingly. It is very critical to understand the
concept of pseudocodes before diving into writing programs using actual codes.
116
References
117
Chapter 9
“
Computers and electronics systems can't understand the syntax that we humans
use to converse with them. It is first converted into a form that they can
understand. And for that purpose, the use of various number systems and codes
across different digital environments came into existence. These number
systems, such as binary, hex, and many others, represent numbers using
multiple symbols that electronic machines understand.
118
Decimal 10 0,1,2,3,4,5,6,7,8,9
Binary 2 0,1
Octal 8 0,1,2,3,4,5,6,7
Hexadecimal 16 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
119
Computer systems are based on binary digits, and for understandability, these
binary digits are converted to a human-readable form. A bit is the smallest unit of
representation of data and holds a value of 0 or 1 at a time, which is
corresponding electrical values for off and on. A byte is a combination of 8 bits
used for the basic unit of information in storage and processing. To exemplify, a
representation for word B or comma or any number can be denoted as a byte.
Bits and bytes are not able to hold massive data and process it. In addition to bits
and bytes, digit systems use the following units of measurements too.
Unit Equivalent
1 kilobyte (KB) 1,024 bytes
1 megabyte (MB) 1,048,576 bytes
1 gigabyte (GB) 1,073,741,824 bytes
1 terabyte (TB) 1,099,511,627,776 bytes
1 petabyte (PB) 1,125,899,906,842,624 bytes
The following section briefly describes the number systems, ASCII code, and their
usage.
120
● Binary Numbers
Binary numbers are a way to express characters in digital systems. It follows
the base-2 numeral system, consisting of the two digits, 0 and 1. This number
system is preferred while designing a digital system due to the implementation
of binary numbers in logic circuits.
Each digit in the system is a bit, and a binary number can consist of many bits.
The below table shows the binary notation of numbers up to 10 in the decimal
number system.
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
121
● Hexadecimal Numbers
Hex numbers, also known as hexadecimal numbers, follow a base-16
numerical system commonly used to represent long strings of binary
numbers. This system uses 16 digits. The below table represents decimal
numbers 0 to 15 in the hexadecimal notation.
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
122
13 D
14 E
15 F
● ASCII Code
ASCII or American Standard Code for Information Interchange is a globally
followed standard for computers and the internet to assign characters in
256 slots in an 8-bit code. Out of the 256 characters, only 128 characters
are standardized by ASCII, and the first 32 characters are control
characters.
123
Since the ASCII code was developed as per American English, it does not
include some European language codes. However, it has lowercase,
uppercase, and special characters. ASCII code is the lowest common
denominator to represent textual information and is followed by most
systems globally.
124
Bacon code, the predecessor of ASCII code, developed by Francis Bacon in 1626 using bilateral steganography.
Conversions
125
126
For instance, take the binary number 1000101001012. The binary digits will
be separated into four groups to convert it to hexadecimal, as shown here.
1000|1010|0101
8|A|5
8A516
127
which will then be replaced by corresponding ASCII value from the ASCII
table.
On converting each octet into a decimal value, the resultant output will be
65 66 67
When the decimals are replaced by ASCII codes available from the table,
the final ASCII code will be
ABC
52 | 69 | 63 | 68
128
Using the ASCII table for equivalent hex numbers, the final ASCII code will
be obtained as
Rich
For instance, the conversion of the ASCII text Pla to the corresponding
binary code is:
● ASCII To Hexadecimal
First, an ASCII code will be taken of each character from the table and
converted to the equivalent decimal value. And then, the decimal value will
be converted to equivalent hexadecimal, and this process continues until
every ASCII code has been converted to hexadecimal.
65
129
65 = 16 x 4 + Remainder 1
4 = 16 x 0 + Remainder 4
41
Final Words
Computers and digital systems use a base-2 number system. The number system
has been of utmost priority among IT experts and has been taught to engineers
and mathematicians since it forms the foundation for electronic devices. Newer
number systems could be developed in the future for quantum computing-based
systems. Still, traditional methods using binary, hexadecimal, and ASCII codes will
be the foundation, and newer systems will be based on them.
130
131
References
132
9. Elprocus. (2020). Hexa to ASCII & ASCII to Hexa Conversion with Example.
https://www.elprocus.com. Retrieved August 26, 2020, from
https://www.elprocus.com/hexa-to-ascii-and-ascii-to-hexa-conversion-with-
example/
133
Chapter 10
Introduction To Programming
“
Computers and other electronic systems are used for different purposes at
home and office. Engineers use it to design, develop, and implement software
or design buildings. At home, it can be used for browsing the internet or
educational purposes. The base of the computer is the programs that instruct
the digital systems.
The computer's hardware alone is not capable of performing even a single action.
Any hardware must be supported by coded instruction that guides the system.
Programs, also collectively called software, contains a set of instructions that a
computer follows. Such instruction blocks are developed by software developers
using various languages, which hide the back-end from casual users. The users can
browse the software using the GUI (Graphical User Interface). Common examples
of computer software are Microsoft Word, Zoom application, and Norton anti-
virus. There have been thousands of languages developed to aid developers and
system administrators from FORTRAN to the Python programming languages.
Some languages were designed for scientific research purposes, whereas some
were intended for application development, and so on.
134
Introduction To Programming
Initial computer programs were written in machine language, which was coded
using binary numbers. Later on, assembly language was used for programming,
which specified instructions in text format such as ADD, SUB, etc. Around 1957,
high-level programming languages that simplified the complexity of coding were
introduced. FORTRAN was the earliest high-level language used for development
in addition to LISP and COBOL.
A program will always have some inputs which will be processed to produce a
predefined type of output. Today's modern high-level languages are supposed to be
readable by professionals to analyze and debug the source code. In addition to
readability, computer programs also possess the following features.
135
Since the usage of high-level programming languages is more and computers can
understand only binary language, many language-translating tools have been used
for conversions, as given below.
136
• Compilers: Compilers initially converts the whole program into binary and
then executes in one go. If errors are detected, then it will be flagged for
the users.
Computer programs are developed in a step by step sequence, and each stage
requires expert knowledge from the team members of the project. The main six
steps in the programming development lifecycle are as follows.
137
138
A program receives some input and performs logical calculations on them and
processes them before generating some output for the end-user. In addition to
the three stages, programs store the information temporarily for using it in the
succeeding steps.
Input is the information given to the program for processing, and it is fed into the
program using input statements in the code. The inputs given in human-
understandable form will be converted into binary code before processing.
The processing phase takes place in the CPU (Central Processing Unit) inside the
computer and involves converting raw data into informative data. During
processing, data will be temporarily stored for future reference or when the
software crashes. CPU uses CU (Control Unit), Memory, and ALU (Arithmetic And
Logic Unit) for data processing in different stages.
In the IPO (Input-Processing-Output) model, the output is the final stage in which
the results generated will be displayed for its users. The final product will be in
human-understandable form after conversion from binary code. Developers will
predefine the output type before executing the program. A feedback channel is
sometimes attached to some IPO model to rectify the error rate. Alternatively,
139
the output feedback can also be used as input at the next iteration of the
program.
• Determining The Inputs And Data Flows: Input types can be derived from
flowcharts, and programmers can understand how data flows and how
140
• Develop The Logic: Logical definition of code ensures relevant output with
the least utilization of resources. In other words, developing logic and
connecting separated blocks ensure the appropriate working of the code.
Final Words
Programs are the core of any computer system today. If there are no instructions,
hardware alone will be meaningless, unless it is a mechanical system. To address
varying environments, newer forms of programming languages have been
evolving. In addition to coding, developers also have to deal with gathering
information and analyzing it to design an efficient program. It is expected that, in
the future, newer programming languages will evolve that will enable even non-
technical professionals to code sophisticated projects in no time.
141
The Hexcode Of The Brain Virus That Attacked Users Back In 1986
Image source: The Vintage News
142
References
[2] "What Is the Software Development Life Cycle?" Husson University Online,
https://online.husson.edu/software-development-cycle/ (Accessed on: Sept. 9,
2020)
143
Chapter 11
“
Every operating system requires its users to interact with a shell indirectly.
Users who operate Ubuntu, Linux Mint, or other Linux variants interact with the
shell whenever they use the terminal. We discuss the basics of shell
programming in this chapter.
Before understanding the basics of shell scripting, one needs to get familiar with
the following terms related to the Operating System (OS) of a computer.
Kernel
The kernel is the computer program that forms the core of your computer's
operating system. It maintains complete control over every aspect of the system. In
a Linux system, it is responsible for managing the following resources:
• File management
144
• Process management
• I/O management
• Memory management
• Device management
Shell: The particular user program which offers the users interface for interacting
with the operating system is called a shell. It plays the role of converting the
human-readable commands from the user to kernel language. Hence, it can be
called a command language interpreter executing commands which it reads from
input devices like keyboards. It starts running as soon as the user logs in or opens
the terminal.
145
Terminal: Terminal can be defined as a program that runs a shell or simply the
interface, which gives you access to the command line.
Shells are interactive, and they execute commands after accepting them as input
from the user. But, what to do if you wish to run a set of commands routinely? You
will have to type all the commands every time in the terminal.
However, to avoid this repetitive work, you can type the commands in a file and
then execute them in a shell as the shell can also take inputs from a file. These files
which contain commands as inputs in a file are known as shell programs or shell
scripts. The shell scripts have a similar syntax to other programming languages.
Hence, students who have experience writing programs in Python, C/C++, etc. find
it easy to start with shell programming. It comprises of the following elements –
146
‘Bash’ is a default shell on Linux operating system and macOS. Git Bash is a
package that installs Bash for you on a Windows operating system and some
commonly-used bash utilities. Git Bash is an application for Microsoft Windows
environments that provides an emulation layer for the Git command-line.
Git command-line provides you with an environment within which you can run
your shell commands.
Before you start writing and executing your first ‘bash’ script, you’ll need to install
Git bash. You can install Git to run your shell commands in three simple steps:
147
Every object in the Linux System gets handled as a file, including the input and
output processes. A shell script is a file that contains various ASCII text in it. In
order to create a shell script, we can use any text editor or a word processor. Here
is the step-by-step procedure to start writing your bash scripts:
Once you have downloaded and installed Git Bash, it will look like this:
Input/Output Techniques
Linux uses a file descriptor for identifying file objects. It refers to a non-negative
integer that specifies the open files uniquely. Hence, each process can have a
148
maximum of nine file descriptors open at a particular time. The first three
descriptors (0,1,2) are reserved for special purposes. These unique descriptors are
the ones responsible for handling the input and output from the script.
Start
STDIN
(Input)
STDERR
If ‘Error’
(Output)
Yes
No
STDOUT
(Output)
End
149
What is STDIN?
The STDIN file descriptor is used to reference standard inputs to the shell. Since
the keyboard is the standard input for the terminal interface, the shell will receive
all information on the STDIN file descriptor.
STDIN is needed because it processes every character as the user types it. The
input redirect signal (<) commands the shell to replace the file referenced in the
redirection with the standard file descriptor. It will retrieve the file's data, just like
the user would have typed on the keyboard. If the programmer does not specify
any file on the command line, the bash command will accept STDIN input.
Here’s an example showing the use of cat command in which the shell enters data
from STDIN:
$ cat
this is the first test.
this is the first test.
this is the second test.
this is the second test.
The cat command will accept the input from STDIN if it sits on the command line
by itself. It will echo the displayed line as the user enters each line. Programmers
can also use the redirect symbol if they want other files to input the cat command.
For example:
150
151
What is STDOUT?
STDOUT stands for standard output. The STDOUT file descriptor is used for
referencing the standard output in the shell. The standard output for a terminal
interface is the terminal monitor. The shell outputs that include the programs and
scripts that the user runs in the shell get directed to the monitor.
STDOUT is needed to store the text output of a command in the stdout stream. The
STDOUT file descriptor receives outputs from most bash commands by default.
However, programmers can change redirect the output by using output redirection.
$ ls -l > test2
$ cat test2
total 20
-rw-rw-r-- 1 rich rich 53 2020-09-17 11:30 test
-rw-rw-r-- 1 rich rich 0 2020-09-17 11:32 test2
-rw-rw-r-- 1 rich rich 73 2020-09-17 11:23 testfile
$
The output redirection symbol will direct the output to the redirection file
designated by the shell, which otherwise would have gone to the monitor.
Programmers can also append data to the file. For example:
152
The who command will generate an output that will get appended to the data
present in the test2 file. However, the users will run into a problem if they use
standard output redirection. For example:
The shell will not redirect the error to the output redirection file if there is an error.
Although there was an output redirection file that the shell created, the error
message will appear on the monitor.
153
What is STDERR?
STDERR file descriptor is the one that the shell uses to handle error messages. It is
used to reference the standard error output. Whenever a command results in an
error, the corresponding error message is stored in this stream.
All the error messages that the shell generates or the scripts that it runs get
redirected to the location defined by STDERR. Although the file descriptor values
for STDERR and STDOUT are different, STDERR will redirect all the error
messages to the same place as STDOUT. Hence, all error messages will go to the
monitor by default. As evident from the previous example, even if the user
redirects the STDOUT file descriptor, the STDERR will remain the same (the
monitor display).
Variables are used to store data that are referenced and manipulated during a
computer program's execution. A variable's type determines the kind of values the
variable can hold and the operations that can be performed on it.
Variables play a crucial role in every programming language. They act as a means
to reference a character or numeric value in a shell script. However, contrary to
formal programming languages, programmers do not need to declare the type of
variable in a shell script.
154
OSTYPE=Linux OS type
155
2. User-Defined Variables:
They are the variables that the users define. The shell script allows the
programmers to define their unique set of variables for storing data temporarily
and using it throughout the script. Thus, the user-defined variables make shell
script analogous to a computer program. They can be a text string of maximum:
• 20 Letters
• 20 Digits
• An underscore character
An important point to note is that these variables are case sensitive. For instance,
Var1 is different from var1.
Users can define a variable using the ‘=’ operator, followed by assigning a value to
a variable name. A variable name refers to a series of alphanumeric characters that
start with '_' or a letter. The shell script treats all variables as text strings unless the
user specifies them to be treated as numeric. For example:
$ myvar=greetings
156
$ mycount=1
In case the user needs to include spaces in-between values, they can surround it by
double-quotes. For example:
Accessing a Variable
The shell script de-references a variable name by adding the prefix $. To print the
variable's value, use the 'echo' command. For example:
$ echo $myvar
greetings
If there is the ‘expr’ command, the script will treat the variable as a numeric value.
For example:
$ expr $mycount + 2
In case the variable is not followed by a space, surround it with spaces. For
example:
$ echo ${myvar}ss
greetingsss
Special characters, for example, ‘$’ retain their meaning in double-quotes. For
example:
157
$ myvar2=”$myvar everyone!”
$ echo $myvar2
greetings everyone!
Single quotes can be used if you want to treat special characters in their literal
sense. For example:
$ myvar3=’$myvar everyone!’
$ echo $myvar3
$myvar everyone!
158
Final Words
Shell programming can perhaps be called as the first step into the world of
programming. It is crucial to get familiar with the basic terminology and shell
scripting before deciding to move on to more complex programming.
159
• It is prone to costly errors. Even a single mistake can change the command.
160
References
161
Chapter 12
“
Various operators exist in Bash, which programmers can apply for performing
multiple operations using the Bash script. Fundamental knowledge of these
operators is essential for computer programming.
Variables are an integral part of every program. However, they only become
valuable when programmers can perform various operations with them. Hence,
many ‘operators’ are available in any programming and scripting languages
(including the Linux Shell) for programmers to perform the intended functions.
What Is An Operator?
162
#!/bin/bash
var2= $ ((200+300))
echo $var2
var3=$(( 5*3 ))
echo $var3
var4= $((40/6))
echo $var4
163
Types Of Operators
It must be clear by now that operators are an essential part of any programming
syntax, as programming itself will be non-existent without them. Various operators
are entrusted with their respective functions, such as arithmetic, relational,
Boolean, bitwise, and file testing. Before going into the detailed description, one
must first know about Unary and Binary operators. Unary operators are applied to
one argument, and programmers often use them to verify the file status (for
example, does a particular file exist?). Binary operators are applied to two
arguments, and programmers use them as part of arithmetic comparisons or strings
(for example, b is bigger than c).
Arithmetic Operators
Arithmetic Operators are used when there is a need to perform arithmetic functions
on variables and constants. The following table contains the list and a description
of the seven different Arithmetic Operators.
Operator Purpose
Addition Operator (+) The binary operation is used for adding two operands.
Subtraction Operator (-) The binary operation is used for subtracting one
operand from another.
Multiplication Operator (*) The binary operation is used for multiplying two
operands.
164
Division Operator (/) The binary operation is used for dividing one operand
from another.
Modulus Operator (%) The binary operation is used for finding the remainder
of two operands.
Increment Operator (++) The unary operator is used for increasing the value of
an operand by one.
Decrement Operator (– –) The unary operator is used for decreasing the value of
an operand by one.
Example:
A=‘expr $x + $y’
S=$(($x - $y))
M=$(($x * $y))
D=$(($x / $y))
let “P = $x ** $y”
165
Output:
166
Relational Operators
Relational Operators make various comparisons between two values and return a
‘true’ or ‘false’ as a result based on the comparisons. The following table contains
the list and description that shows the relevance of the six Relational Operators in
programming.
Operator Description
‘==’ Operator It compares two operands. It returns ‘true’ when they are
Equal to equal; otherwise, it will return ‘false.’
‘!=’ Operator It returns ‘true’ when the two operands are not equal;
Not Equal to otherwise, it will return ‘false.’
‘< 'Operator It returns ‘true’ when the first operand is less than the
Less than second operand; otherwise, it will return ‘false.’
‘<=’ Operator It returns ‘true’ when the first operand is less than or equal
Less than or equal to to the second operand; otherwise, it will return ‘false.’
‘>’ Operator It returns ‘true’ when the first operand is greater than the
Greater than second operand; otherwise, it will return ‘false.’
‘>=’ Operator It returns ‘true’ when the first operand is greater than or
Greater than or equal to equal to the second operand; otherwise, it will return
‘false.’
167
Example
if(( $a==$b ))
then
else
fi
if(( $a!=$b ))
then
else
fi
if(( $a<$b ))
168
then
else
fi
if(( $a<=$b ))
then
else
fi
if(( $a>$b ))
then
else
fi
if(( $a>=$b ))
169
then
else
fi
Output:
170
Boolean Operators
Boolean or logical operators take in Boolean values of two elements and return a
Boolean result. Boolean Operators are of three types, as mentioned in the table
below:
Operator Description
Logical AND (&&) Operator It is a binary operator and will return ‘true’ if
both the operands are ‘true’; otherwise, it will
return ‘false.’
Not Equal to (!) Operator It is a unary operator and will return ‘true’ if
the operand is ‘false’ and ‘false’ if it is ‘true.’
These operators form the basis to make decisions in a shell program and execute
different sets of instructions based on them. They are also called Logical Operators
and are used for flow control.
171
Example:
then
else
fi
then
else
fi
if(( ! $a == "true" ))
then
172
else
fi
Output:
173
Bitwise Operators
Operator Description
Bitwise XOR (^) Operator It performs binary XOR operation bit by bit on the
operands.
Bitwise AND (&) Operator It performs binary AND operation bit by bit on the
operands.
Bitwise complement (~) It performs binary NOT operation bit by bit on the
Operator operand.
Right Shift (>>) Operator It will shift the operand’s bits to the right by the
number of times specified by the right operand.
Left Shift (<<) Operator It will shift the operand’s bits to the left by the
number of times specified by the right operand.
174
Programmers use Bitwise Operators for changing the individual bits in an operand.
They can perform bitwise operations on bit patterns using these operators.
Example:
bitwise Complement=$(( ~a ))
175
Output:
File Test Operators are a set of operators specifically meant to evaluate various
statuses and properties of files. The following table lists some types of file test
operators:
Operator Description
176
writing to them.
Linux and Unix OS consider everything as a file. Hence, it becomes necessary for
programmers who use Bash files to perform some tests on the files. File Test
Operators help them test particular properties of a file.
Example:
177
if [ -e $FileName ]
then
else
fi
if [ -s $FileName ]
then
else
fi
if [ -r $FileName ]
then
else
echo "The given file does not have read access. "
fi
178
if [ -w $FileName ]
then
else
echo "The given file does not have write access. "
fi
if [ -x $FileName ]
then
else
fi
Output:
179
Bash offers programmers an essential feature - the ability to use a label or a name
for referring to some other quantity as a value, command, or operator. It is called
‘assigning variables.’
• Setting a variable
The following example shows how users can assign “greetings” to the variable
var_a, and “30” to another_var.
var_a=“Greetings”
another_var=30
However, users need to be careful about the syntax they use for setting variables.
Bash does not allow white space between a variable name, the equal sign, and the
value. Hence, Bash will throw an error for the following commands:
var_a= “greetings”
var_a = “greetings”
var_a =“greetings”
180
var_a=“greetings”
another_var=30
echo $var_a
greetings
echo $another_var
30
echo $var_a$another_var
greetings 30
181
• The "My Dear Aunt Sally" mantra for the arithmetic operations. (multiply,
divide, add, subtract)
• Low precedence is given to compound logical operators like &&, ||, -a, and -
o.
• The order of execution of equal-precedence operators is left-to-right
182
Final Words
Operators have an indispensable position in shell scripts as they are the elements
that give value to the variables and constants. In other words, operators infuse
functionality into the program. It is interesting to study the various types of
operators and understand their functional relevance. A strong knowledge base of
operations is also an essential tool for an efficient programmer.
183
a=10
b=$(( $a<0&&$a<100 ))
echo $b
exit 0
Answer: The condition' $a<0’ is false; hence, the logical AND operator will
provide the output 0.
184
References
185
Chapter 13
“
Computer programs use logical and arithmetic operators to arrive at proper
conclusions. One should know the basic concepts of the decision control
structure in Shell, of which truth tables and conditional statements are critical
components.
A truth-value can help test the validity of any argument. Every statement can either
be true or false. The truth-value is the truth or the falsity of every proposition.
A truth table consists of rows and columns. The columns correspond to the number
of compound statements. If there are two statements, there will be two columns,
and so on. The rows constitute the possible combinations (truth or falsehood).
Thus, if the compound has two propositions, there will be a maximum of four
possibilities. Therefore, there will be four rows to the truth table.
186
A Boolean or bool is a data type with two possible values: true or false, and it
represents the two truth values of logic and Boolean algebra. There are primarily
two types of Boolean Values, True and False (2).
Boolean Values are used as values of the expressions with "Yes" or "No" as its
answers. In computer circuits, these values are represented by a "1" or "0" where
"1" represents 'True' or 'Yes,' and "0" represents 'False' or 'N'.
The Boolean expression evaluates to a Boolean value. The following are the
Boolean expressions supported by Shell:
187
• Logical negation (!): It will invert a false condition into true and vice versa.
• Logical AND (-a): The condition will be true when both of the operands are
true.
• Logical OR (-o): The condition will be true when either one of the operands is
true.
In this example, we use the logical negation (!) to determine whether the two
values are equal or not.
#!/bin/sh
# Read the user input
echo “Enter first number”
read x
echo “Enter second number”
read y
if [ $x != $y ]
then
echo "$x != $y : x is not equal to y"
else
echo "$x != $y: x is equal to y"
fi
188
Conditional statements are useful for making decisions based on the conditions. If
there are no conditions, the conditional statements execute sequentially. If there is
a condition, the execution flow will change, depending on the result evaluated by
the condition.
What is an If statement?
Please note to include a space between the enclosing brackets and the expression.
189
Syntax If (Expression)
Then
Statement
fi
The If statement modifies the execution flow of the program, depending on which
condition is satisfied. The condition is evaluated first before the execution of any
statement inside the body of It. The programmers use conditional expressions with
the [[ compound command and the [ builtin commands.
In this example, we will display a statement if the number is greater than 100.
if [ $x -gt 100 ]
then
echo “That is a large number.”
fi
190
Flowchart
The case statement works like a switch statement in Bash. It executes a block of a
particular pattern if the specified value matches the pattern. When there is a match,
it executes all the associated statements up to the double semicolon (;;).
case in
*)
Default statement need to execute
esac
191
The Switch statement is an alternative for the "If-Else" statement. There is an issue
with the "If-Else" statement. The program becomes more complicated if there are
more alternative paths. Using multiple "If-Else" statements can make the program
difficult to comprehend. The ideal solution is the switch statement.
This flowchart of a simple switch statement should help you understand it better.
192
#!/bin/bash
read COUNTRY
case $COUNTRY in
UK)
echo -n "English" ;;
Romania | Moldova)
echo -n "Romanian" ;;
echo -n "Spanish";;
*)
echo -n "unknown"
;;
esac
193
Conditions
The If statement should be used when making a comparison and controlling the
program flow is required. There are three types of Bash conditions: string
conditions, number conditions, and file conditions (3).
• = or == means equal to
• != means not equal to
• < means less than
• > means greater than
• -z test that the string is null
• -n test that the string is not empty or null
#!/bin/bash
echo "Please enter first number"
read x
echo "Please enter second number"
read y
if(( $x lt $y ))
then
echo “$x lt $y: x is less than y.”
else
echo “$x lt $y: x is not less than y.”
fi
195
#! /bin/bash
file_name=$F
if [ -e $file_name ]
then
echo -e "File $file_name exists"
else
echo -e "File $file_name doesnt exists"
fi
196
We have seen that the "If" statement tells the program to execute a block code if a
specific condition is true. If it is false, it suggests an alternate route.
Conditional statements will take you to the logical conclusion. A simple example
would be as follows (4).
"If it rains outside, I will take an umbrella, but if it is sunny, I will take my
sunglasses." You can do things conditionally using the "If" and If Else" statements
along with conditional statements.
197
#! /bin/bash
echo "Please enter degrees outside"
read degree
echo "Please enter number of clouds"
read cloud
if [ $degree -gt 35 ] && [ $cloud -lt 5 ]
then
echo "Wear sunscreen and take glasses!"
else
echo "No for sunscreen, Sunglasses would do!"
fi
198
#!/bin/bash
inp1=10
inp2=12
echo "1. Add"
echo "2. Subtract"
echo -n "Please choose [1 or 2]? "
read choice
if [ $choice -eq 1 ]
then
echo "Addition Result " $(($inp1 + $inp2))
else
if [ $choice -eq 2 ]
then
echo "Subtraction Result " $(($inp1 - $inp2))
else
echo "Invalid input"
fi
fi
199
We have seen that computer programs use conditional statements for selecting the
right path to proceed. If the program has to choose between one or two paths, it is a
conditional statement. We use the "If Else" statement.
On the other hand, if the program selects multiple paths to proceed, it uses nested
conditional statements (5).
200
negative, or none of the above. You can see that the numbers have to select from
three paths. The flowchart would look like this.
Given below is the code of the flowchart displayed above. Please note that there
must be a closing “fi” statement for every “if” statement that you will open. One
single “fi” is not enough for the multiple “if” statements and will throw a syntax
error.
#!/bin/bash
echo "Enter a Number"
read value
if [ $value -lt 0 ]
then
echo "The number is Negative"
elif [ $value -gt 0 ]
then
echo "The number is Positive"
else
echo "The number is Neither Positive Nor Negative"
fi
201
Final Thoughts
Computer programs use a lot of logic and arithmetic calculations to arrive at proper
conclusions. If it were not for these logical and arithmetical operations, there
would be utter chaos. Thus, one can deduce that truth tables and conditional
statements are crucial aspects of shell scripting.
202
Can you go through this simple program below and see what the output of this
program is?
#!/bin/bash
num1=10
if [[ $num1 -eq 5 ]]
then
then
else
fi
203
Answer:
The exit_status will be zero. Since 10 is equal to 10, the output will be that the
number is matched in elif block.
References
204
Chapter 14
“
All programming languages allow us to make decisions that are based on
certain pre-set conditions. The term condition refers to an expression that
evaluates a Boolean value – True or False. Thus, the decision and logic that a
programmer put in his script define how smart the program turns out. The
decision statements which bash shell supports are the if and switch (case)
statements. We will cover two detailed examples of each of these in this chapter.
Pseudocode
The following code will output "Yes" if the two numbers are equal and "No" if
they are not.
205
Flowchart
206
Final code.
#!/bin/bash
read first
read second
if [ $first == $second ]
then
echo "YES"
else
echo "NO"
fi
Practice Problems
Problem-A
207
if [expression];
then
fi
• Note that the 'expression' will get executed only if the if condition evaluates
to true. People often get confused when it comes to writing the if statement:
if (condition)
if ((condition))
if [condition]
if [[condition]]
208
• We will use the cd command to ensure the shell returns to the home
directory regardless of its current directory.
• The Is command will allow us to verify if the file exists.
• We have used multiple if conditions for solving the problem.
Problem-B
The next example requires the user to input a student's marks and check if marks
are greater or equal to 80 then print "Very Good". If marks are less than 80 and
greater or equal to 50, then print "good" and so on.
209
Problem-C
In this example, we focus on the switch case statement in Bash. The program will
allow the user to input a month name. It will then display the international event
in the chosen month. If there is no defined pattern in the script, it will display "No
match found."
• The case statement will start with the 'case' keyword, followed by the case
expression (the month name), and the in keyword. The statement will end
with the esac keyword.
• The | operator can separate multiple patterns.
• The ) operator will terminate a pattern list.
• There can be special characters in a pattern.
• A pattern, including its associated commands, is called a clause.
• Each clause terminates with ;;.
• The commands which correspond to the first pattern, which will match the
expression, get executed.
• (*) acts as the final pattern that defines the default case when no other
cases match.
• We use the "shopt -s nocasematch" to match the pattern irrespective of its
case.
210
Problem-D
It will allow the user to choose from the three-car brands, namely, Mercedes,
Audi, and BMW, and display the selected car company's headquarters.
• The switch case statement in Bash allows the script to compare different
values against a variable, easier than the if conditional statement.
• It has a similar concept to the C or JavaScript switch statement. The Bash
case statement is different from the other two. It stops searching for the
pattern match after it has executed statements associated with a matched
pattern.
• In this example, we will first display a menu using the printf command and
ask the user to key-in the brand's name.
• After that, the case conditional will follow, similar to the previous example.
• Note that we do not use the wildcard asterisk symbol (*) as the final
pattern in this example.
211
Problem-A Solution
Pseudocode
The following code will read the file name and display the permissions it has:
212
Flowchart
213
Shell Script
#!/bin/bash
cd
ls -l
read -p "Enter a file name: " file_name
if [ -e $file_name ]
then
echo "file exists!"
if [ -r $file_name ]
then
status="readable "
fi
if [ -w $file_name ]
then
status=$status"writable "
fi
if [ -x $file_name ]
then
status=$status"executable"
fi
echo "file permission: "$status
else
echo "file does not exist"
fi
214
Problem-B Solution
Pseudocode
The following program will input a student's marks and check if marks are greater
or equal to 80 then print "Very Good". If marks are less than 80 and greater or
equal to 50, then print "good" and so on.
215
Flowchart
216
Shell script
#!/bin/sh
read marks
if [ $marks -ge 80 ]
then
then
echo "Good"
then
else
fi
217
Problem-C Solution
Pseudocode
The following program will read the input month from the user and display
important events in the chosen month (until July).
Flowchart
218
219
Shell Script
shopt -s nocasematch
echo "Enter name of the month"
read mnth
case $mnth in
January)
echo " 24th January is the international Day of
Education."
;;
February)
echo " 20 February is the World Day of Social
Justice ."
;;
March)
echo "8th March is the International women’s day."
;;
April)
echo "7th April is The World Health Day";;
May)
echo "The 15 May is the International Day of
Families"
;;
June)
echo "20th June is the World Refugee Day"
;;
July)
echo "11th July is the World Population Day"
;;
*)
echo "No matching information found"
;;
220
Problem-D Solution
Pseudocode
The following program will allow the user to choose from the three car brands,
namely Mercedes, Audi, and BMW, and display the selected car company's
headquarters.
221
Flowchart
222
Shell script
#!/bin/bash
clear
case "$CARS" in
esac
223
Final Words
224
Hint: It is an if-else single decision problem. Use the '-d' file-test operator.
Solution:
if [ -d "/path/to/dir" ]
then
echo "Directory /path/to/dir exists."
else
echo "Error: Directory /path/to/dir does not exists."
fi
225
References
226
Chapter 15
“
In computer programming, iteration refers to a process where the program
repeats a set of structures or instructions in a sequence, the number of times
specified by the user, or until the program meets a particular pre-set condition.
When the program executes the first set of instructions again, it is called
iteration. Similarly, when the program executes a sequence of instructions
repeatedly, it is known as a loop. In this chapter, we will study the loops in Bash
in detail.
What is Iteration
Most languages, including Bash, uses the concept of loops. For example, it will
become cumbersome to type the same code with slight variations twenty times if
we want to repeat a task twenty times. Instead, we can use the FOR and WHILE
loops in Shell!
227
FOR loop
FOR loops in Shell keep iterating a set of values until the list gets exhausted.
Syntax
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done
A list refers to a list of names. If you omit the "in", the list will default to the
quoted command-line arguments, or "$@". "$@" is a positional parameter that
treats all parameters as a quoted string. In simple words, all the parameters in the
quoted string will be seen as separate words. It is preferable to define the "in" list
for clarity in the code. For example:
do
echo $user
done
228
The example follows the list of values that are received from the command line. If
'in list' is missing, your loop will operate on '$@'
for i in "$@"
do
echo $(($i * 2))
done
#without “$@”
for a
do
echo -n $(($a * 3)) " " # -n don't add new line
done
Forloop.bash 1 2 3
You may also save a list in a variable and iterate through the variable, and access
each element using a FOR loop, as it is shown in the following example.
echo $user
done
229
for file_name in * ; do
if [ -d "$file_name" ]
then
echo "directory $file_name"
else
echo -e "\t$file_name"
fi
done
There is built-in support to set-up ranges using {…} in the Bash version 3.0+
#!/bin/bash
for var in {1..10}
do
echo "Welcome $var times"
done
#!/bin/bash
echo "Bash version is ${BASH_VERSION}..."
for var in {0..10..2} do
echo "Welcome $var times"
done
230
10
#!/bin/bash
for i in `seq 1 10`; do
echo $i
done
Users who are using the latest Bash version (version 2.04 and above) can use the
latest FOR syntax, which uses double parenthesis ((…)) to perform iteration. It is
similar to the C language.
do
commands ;
done
231
Double parenthesis means that programmers can use the ((…)) syntax construct to
write the script's expressions. The program executes the initialization part once
when the loop starts. The on any iteration, it evaluates the test part. If the test
evaluation result is true, the program will execute the loop body's commands and
finally update the step part. If the test is false, the loop terminates.
Following is the code to print numbers from 1 to 10 using the new FOR loop.
do
echo $var ;
done
Problem Definition:
Write a program using the FOR loop for spanning through a given list of numbers
(0 to 9)
232
Flowchart:
Code:
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
233
Explanation:
Output
0
1
2
3
4
5
6
7
8
9
234
You can execute a particular set of commands continuously until you reach
specific conditions using the WHILE loop. Programmers generally use this loop
when they want to manipulate the value of a variable repeatedly.
Syntax
while command
do
Statement(s) which must be executed if the command is true
done
Until command
do
Statement(s) to be executed until command is true
done
235
Breaking Statement
The break command causes the iteration to stop and exit the loop.
#!/bin/bash
val=1
do
if [ $val -eq 4 ];
then
break
fi
val=$(($val + 1))
done
236
Explanation:
Continuing Statement
In Bash, you can use the CONTINUE command to skip the remaining statements
in the loop body and continue to the next iteration. In simple words, CONTINUE
in Bash will mean proceeding to the next iteration of the loop. Traditionally, this
statement is called CONTINUE, similar to C language.
In the following example, when the current iterated item reaches the value 2, we
use the CONTINUE statement to make the program skip the remaining statements
and return to the loop's start and continue the subsequent iteration.
var=0
((var++))
continue
fi
done
237
Output:
Number: 1
Number: 3
Number: 4
Number: 5
All Done!
Infinite loop
An infinite loop is an endless loop that never meets its condition. An infinite loop
runs forever unless an unexpected event such as shutting down a computer occurs.
An infinite loop can waste computer resources such as memory and CPU time,
preventing other programs from running smoothly.
while :
do
echo "Pres CTRL+C to stop..."
sleep 1
if [ 0 -eq 1 ] #bad condition
then
break #Stop this loop
fi
done
238
Problem definition:
Flowchart
Code
i=1
while [ $i -le 10 ]
do
echo "$i"
((i++))
done
239
Explanation:
As seen above, we have defined variable i, whose value will increment with each
iteration. The condition part will test its value and will display its value as long as
the condition is True. When the loop is executing, the value of i is checked to
ascertain if it has a value less than 10. If the value is less than 10, i.e., the condition
is TRUE, the exit status is zero. In such cases, the program will display the current
value of i and increment it by 1 later.
Output
1
2
3
4
5
6
7
8
9
10
Problems to Solve
• Q.1 Use the FOR loop to print numbers from 1 to 50, which are divisible
by 9.
• Q.2 Use the WHILE break statement to add two numbers and skip the while
loop when the user enters -1.
• Q.3 Explain by modifying the simple example of WHILE loop (2.b.4), what
this WHILE with "do" keyword behaves if the condition is False upfront?
240
Solutions
Q1-Solutions
for x in {1..50}; do
continue
fi
done
For numbers that are not divisible by 9, the CONTINUE statement will skip the
echo command, and the control passes to the next iteration in the loop.
Output
Divisible by 9: 9
Divisible by 9: 18
Divisible by 9: 27
Divisible by 9: 36
Divisible by 9: 45
241
Q2-Solutions
#!/bin/bash
while :
do
if [ $x -eq -1 ]
then
break
fi
ans=$(( x + y ))
echo $ans
done
Output:
242
Q3-Solutions
i=11
while [ $i -le 10 ]
do
echo "$i"
((i++))
done
Output:
As you can see from the output, the program will not display the variable's value at
all. Since the loop's condition is initially false, none of the statements inside the
loop will be executed.
243
Final Words
In this chapter, we saw how you could perform basic iterations using the Bourne
Shell programming. We learned that there are two types of loops used in Bash, i.e.,
the FOR loop and the WHILE loop. We also reviewed different kinds of FOR
loops in various Bash versions plus how-to utilize break and continue statements.
244
References
245
Chapter 16
“
We learned in the previous chapter about iterations in Bash script. One can use
the FOR, WHILE, or UNTIL loops to define iterative statements or loops in
Bash. In this chapter, we will supplement our knowledge of iterations by looking
at some advanced examples.
246
Problem A
Use the FOR loop in Bash to write a program without a list and read command-line
arguments.
Steps:
Problem B
Use the infinite FOR loop to display a five lists menu and display a specific
message for each number (5 to exit).
Steps:
1. We use the infinite FOR loop to perform repetitive tasks multiple times.
2. The loop terminates when a particular condition appears.
3. We will not define a termination condition in this loop.
4. The loop will display a menu for five lists until the user presses the number
5.
5. For other numbers, the program will display a specific message (from 1 to
4).
6. After that, it will display the menu again.
7. The empty for expression (( ; ; )) is used to define an infinite loop.
8. Since we are using the case command inside an infinite loop in this example,
we will use the exit command to terminate the loop.
247
Problem C
Use the CONTINUE statement in the WHILE loop to display a set of 5 numbers
and omit the third step.
Steps:
1. In this program, we will use the CONTINUE statement in the WHILE loop.
2. The program will iterate five times without printing all of the five positions.
3. We will define the condition [ $i -le 5 ] inside the WHILE loop.
4. The program will check the condition [ $i -le 5 ] before executing the
commands.
5. The program will execute the commands between do and done for as long as
the condition [ $i -le 5 ] is true.
6. We will use the CONTINUE statement in the third position. Thus, the loop
will skip the text of the third position and continue to the next iteration.
7. We will define the expression inside the if..then..fi statement within the
WHILE loop.
8. If the expression is true; [ $i == 3 ], the loop will execute the CONTINUE
statement and omit the third step.
9. If the expression is false, then the program will continue to the next iteration.
Problem D
Use a variable in the UNTIL loop to decrement a number initialized at ten until it
reaches the value 5.
Steps:
1. In this program, we will use the $var variable for controlling the iteration of
the loop.
2. We will initialize the loop at 10.
3. The loop will carry on the iteration six times.
4. We use the $echo command for printing the value of $var after each step.
5. To reach the UNTIL loop's termination condition, the value of $var will
decrement by 1 in each step.
6. We will define the condition [ $var – lt 5 ] inside the UNTIL loop.
7. The loop will check this condition before executing the commands.
248
Problem A Solution:
Pseudocode
The following code will use the FOR command to create a program without a list
249
Flowchart
Script
stp=1
for text
do
if [ $stp -eq 2 ]
then
disp="My favorite color is "
elif [ $stp -eq 3 ]
then
disp="I love "
else
disp="I like "
fi
echo "$disp $text"
((stp=$stp+1))
done
250
Output
Problem B Solution:
Pseudocode
The following code will use the FOR command to create a program to allow the
user to choose from 1 to 5 and display different results.
251
Flowchart
252
Script
for (( ; ; ))
do
echo "1. Print the success message"
echo "2. Print the information message"
echo "3. Print the Warning message"
echo "4. print the error message"
echo "5. To Exit"
echo -n "Select a number from [1-5]:"
read ans
case "$ans" in
1) echo "The Task is Successfully completed." ;;
2) echo "It is an Invalid input";;
3) echo "Your computer is running on low battery";;
4) echo "You submitted a Wrong number of arguments
";;
5) exit 0;;
*) echo "Wrong selection";;
esac
done
253
Output
Problem C Solution:
Pseudocode
The following program will use the CONTINUE statement in the WHILE loop to
display a set of 5 numbers and omit the third step.
254
Flowchart
Script
i=0
while [ $i -lt 5 ]
do
(( i++ ))
if [ $i == 3 ]
then
continue
fi
echo
Output:
255
Problem D Solution:
Pseudocode
The following program will use a counter in the UNTIL loop to decrement the
value of a number 6 times.
Flowchart
Script
var=10
until [ $var -lt 5 ]
do
echo "The current value of the variable = $var"
256
((var--))
done
Output
Final Words
In this chapter, we saw some examples of iterations in detail. The explanations and
pseudocodes, coupled with detailed flowcharts, will help students grasp the idea
behind the code written for each problem. They can start practicing with these
codes only after getting their basics about iterations clear from the first chapter.
257
Exercise:
Below are some additional examples for your practice, which will help bring
further clarity about iterations.
Exercise A:
Allow the user to enter from the following ways of saying hello: howdy, hello,
guten tag, bonjour, gday, and display the result of the language used.
You can use the WHILE loop in this example and include the CASE
statement to define different languages. The code will look something like this:
258
Exercise B:
259
Exercise C:
maximum=5
x=1
y=0
until [[ $x -gt $maximum || $y -gt $maximum ]];
do
echo "x = $x & y = $y."
((x++))
((y++))
done
260
References
261
Chapter 17
“
A set of commands which users can call repeatedly is known as a Bash function.
The functions help in making a Bash script readable and avoid writing repetitive
What Is A Function?
Most people get confused about whether to call Bash functions as functions or
procedures. Strictly speaking, functions are used in programming languages to
return a single value and not any output. A procedure, on the other hand, may
produce an output but does not return a value. They can return a value in one of
the following ways:
• Change a single or multiple variable's states.
• Make use of the exit command to end the script.
• Can be used to update the contents of a file.
262
• Can use the return command for ending the function, and the supplied
value is returned to the calling section of the script.
B. The second format uses the reserved word "function" to start, and then it is
followed by the function name.
function function_name {
commands
}
263
function in Bash script. When you invoke a function, the body of the
function will get executed.
• You must define the function before placing any calls to the function.
• The compacted function or the single line versions must have a
semicolon after the function's last command.
• It is prudent to keep the function names descriptive, in line with the code.
You can call or trigger a function in a Bash script by invoking its name in the
script. Bash treats the function calls as a command. We discuss more on the
syntax of calling a function in section 5. “example_git”
264
Bash allows you to create function files that will store all your functions. These
function files are called function libraries. Then you can load all your functions
into the Bash script. The syntax to load all functions is as follows:
. /path/to/your/functions.sh
function_name () {
<commands>
}
or
function function_name {
<commands>
}
• You can use either of the above two methods to specify a function. Both
of them operate in the same manner, and it's a matter of choice, with no
advantage or disadvantage associated with one method or the other.
• The () brackets may contain arguments in other languages, whereas they
are just for decoration purposes in Bash!
265
• You must define the function in the script before making any calls to the
function.
• To invoke or call a function, type the function name.
The example shows how to define and write a tomrw() function to display
tomorrow's date.
tomrw
#!/bin/bash
tomrw(){
date ++date=’1 day after’;
}
tomrw
The Bash function will return the exit status for the last command it executes,
captured in the $? variable. All non-zero positive integers between the range 1-
255 will indicate a failure, and zero will indicate a successful execution.
However, users can put a return statement inside the script for altering the
266
function's exit status. The following errorfunction script will help clear things
better:
#! /bin/bash
error_script () {
Hello World
return 0
}
error_script
echo "The return status of the error function is:
$?"
Now, when you run the errorfunction.sh bash script, the output will be:
The errorfunction would never return a non-zero exit status if we did not define
the return 0 statement. It is so because "Hello World" results in an error
"command not found."
Hence, we can alter the exit status of functions to return values even when we
know that Bash functions don't return values. The critical point to remember
here is that the return statement terminates a function immediately.
Bash uses entities known as parameters to store values. It can either be a name,
number, or unique character. The parameter which is denoted by a name is also
called a variable. The variable includes a value and zero or more attributes. You
can assign the attributes with the built-in declare command.
267
In Bash scripts, you can define some variables available throughout the script,
known as global variables, and others that are only visible within the block of
the code, known as local variables. The following example will help clear
things better.
#!/bin/bash
pprint()
{
local locvar="Local variable"
echo -e "Value of the Local variable within the function"
echo $locvar
glovar="Global variable changed"
echo -e "Value of the Global variable within the function"
echo $glovar
}
glovar="Global variable"
echo -e "Value of the Global variable before calling function"
echo $glovar
echo -e "Value of the Local variable before calling function"
echo $locvar
pprint
echo -e "Value of the Global variable after calling function"
268
echo $glovar
echo -e "Value of the Local variable after calling function"
echo $locvar
Hence, it is clear from the output that before and after calling the pprint()
function, the local variables have only empty values. Its scope is limited to only
within the function, and it gets vanished outside the function. However, the
global variable updates its value even after the execution of the function.
Recursion
The local function variables offer one feature called self-containment. Any self-
contained function will only use the script's variables to pass to it in the
command line, and it will not use any resources outside the function.
It is the feature that will allow the user to call the function recursively.
Recursion means the function will call itself to reach an answer. Mostly, there is
a base value to which the recursive function iterates down. Advanced
269
5!= 5 * 4 * 3 * 2 *1 = 120
We can reduce the above equation to the following format using recursion:
x! = x * (x-1)!
#!/bin/bash
factorial_num() {
if [ $1 -eq 1 ]
then
echo 1
else
local var=$(( $1 - 1 ))
local res=$(factorial_num $var)
echo $(( $res * $1 ))
fi
}
read -p "Enter a number: " input
factorial=$(factorial_num $input)
echo "The factorial of $input is: $factorial"
Key points to note are:
• You must define a base case to begin a recursive function. It becomes
necessary for ending the chain of calls to the recursive function. In the
factorial () function, we have defined the base case as follows:
270
if [ $1 -eq 1 ]
then
echo 1
• The next step is deriving the recursive case of the factorial function. As seen
above, to find the factorial of a given positive number greater than 1, x,
multiply it with the factorial of x-1.
factorial(x) = x * factorial(x-1)
• Hence, you can derive the recursive case of the script as:
local var=$(( $1 - 1 ))
local res=$(factorial_num $var)
echo $(( $res * $1 ))
As you are aware, Bash does not need you to declare a variable. When you use
a variable inside the script, it will create a variable automatically. Although it is
more convenient, it may lead to unfortunate consequences. An example is a
spelling error that may create an extra variable you did not wish to create.
271
• The function call has a different function than the one you defined.
• Other syntax errors like space between function name and {, case
sensitivity, forgot to use ", etc.
Problems to Solve
1) Write a program to define a function that accepts parameters John and Smith
while calling the function. Represent these parameters by $1 and $2.
2) Use the above example to define a function that will return a value of 10.
Solutions
Q1-Solutions
#!/bin/sh
example1 () {
echo "Hello World $1 $2"
}
example1 John Smith
Q2-Solutions
#!/bin/sh
example2() {
echo "Hello World $1 $2"
272
return 10
}
example2 John Smith
ret=$?
echo "The Return value is $ret."
Q3-Solutions
#!/bin/sh
func_one () {
echo "This is the first function speaking..."
func_two
}
func_two () {
echo "Now, this is the second function
speaking..."
}
func_one
273
References
274
Chapter 18
“
In the previous chapter on functions, we discussed the syntax and basics of
using functions in a Bash script. This chapter will help you apply the gained
knowledge from the previous chapter to write scripts using functions. This
chapter will cover four crucial areas of functions that an aspiring Bash
programmer must be aware of. These are: Passing arguments to a function, set
up a return status for the function, declare local and global variables, and
recursion.
First, let us brush up on our knowledge about functions. You can think of functions
as small scripts within a script. It is a small code that you can call many times in
your script. Functions come in handy when you have certain tasks to perform
several times. They save you from the hassle of writing the same code over and
over again! With that definition in mind, let's get down to business.
Problem A
Write a simple program using functions to pass multiple arguments to the program
and return the values.
275
Learning Outcome: After this exercise, you will gain knowledge about how to
pass arguments to the script. You can use arguments when you want to write a
script that will perform different functions by using these arguments' values.
For passing any number of arguments in the Bash function, you must insert them
right after the function's name. It is important to put spaces between the function
name and the arguments. It is also suggested to use double quotes to prevent the
misspacing of arguments.
• We will define the arguments as $1, $2, $3 ... $n. The console will access the
given arguments in the same sequence, corresponding to the arguments'
position after the function's name.
• You can use the $# variable for holding the positional arguments/ parameters
provided to the function.
o $* with double quotes (i.e., "$*" ) will expand to a single string which
is separated by the space, example, "$1 $2 $n etc".
o $@ with double quotes (i.e., "$@" ) expands to the separate string, for
example, "$1" "$2" "$n" etc.
o $* and $# without any double quotes are the same.
276
Problem B
Write a simple program to set up a return status for a function. Use it to return a
value of 8 for a function.
You can set a return status, which makes the program similar to the one with an
exit status. Thus, after the function is complete, it will show the last executed
statement's status as the return value. For success status, it will return 0, and for
failure, it will return any number between 1-255 range.
• In this program, we will use the 'return' keyword to indicate the return
status.
• We will use the $? variable to display the stored return value (8 in this
case).
• The return statement will terminate the function, and it will work as the
function's exit status.
Problem C
Write a program using functions in a Bash script to declare two variables of the
same name – one global and one local.
277
Learning Outcome: As you are already aware, we can declare a variable inside
a function as a local variable using the local keyword. Bash variables have
dynamic scope. When you declare a variable local to a function, its scope
remains the same until the function returns and calls to other functions. This
exercise will provide a deeper understanding of declaring the local variables
and their use in a Bash script.
• This program will define two variables: one inside the function and the
other outside it.
• Both of these variables will have an identical name, i.e., $tmp.
• The key point to note here is that since one of the $tmp variables is inside
the function and the other $tmp variable is outside the function, they will
not affect each other, even if they have an identical name.
• Thus the $tmp variable inside the function will not affect the $tmp
variable outside the function.
• The local variable is only available to the function and its children
(associated functions which the said function may call). It doesn't affect
the global state of the caller.
• When we define a local variable of a similar name as the global variable
inside the function body, it takes precedence over the global variable.
Problem D
Use functions in a Bash script to show the recursion of a number till it reaches the
maximum value of 5.
278
• First, we need to decide the base case for the recursion. We will add
declare -i counter=0 in the beginning.
• The declare command in Bash allows you to update the attributes applied
to the variables in your script. Additionally, you can use it to declare a
variable.
• Now, wrap the recurse command in the function with an if statement for
limiting the recursion.
• We define the condition of the if statement as $counter -lt 5.
• The function will recurse as long as the counter is less than 5.
• We need to increment the count to ensure that it is increasing. Thus, we
will add ((counter++)). Add it before the recurse command.
• A common mistake done by many is adding incrementation after the
recurse command. If you add ((counter++)) after the recurse command, it
will be of no use. It is so because the script will keep recursing before it
reaches the incrementation. The count will never increase, and shell will
never exit the recursion.
279
Problem-A Solution
Pseudocode
The following is a simple program that will pass multiple arguments to the shell
and return the values later.
280
}
assign value to n1
assign value to n2
invoke the function by assigning values n1 to argument 1 and n2 to
argument 2
Display the result
Flowchart
281
Script
function foo(){
echo $1
echo $2
}
foo 10 20;
foo john doe
function foo(){
local a=$1
local b=$2
local sum=$((a + b))
return $sum;
}
function foo(){
echo $1
echo $2
return $(($1+$2));
}
n1=10
n2=20
foo n1 n2;
echo "$n1 + $n2 = $?";
Output
10
20
10 + 20 = 30
282
Problem-B Solution
Pseudocode
The following is a program that will display 8 as the return status of the function.
Flowchart
283
Script
#!/bin/bash
func_stat () {
echo Greetings $1
return 8
}
func_stat User
func_stat Reader
echo “The previous function returned a value of $?”
Output
Problem-C Solution
Pseudocode
The following program will declare two variables with a similar name – one local
and one global, and assign the value 10 to the local variable and 4 to the global
variable.
284
Script
#!/bin/bash
myfunc() {
local tmp=$(($tmp + 10))
echo "The Temp from inside the function is $tmp"
}
tmp=4
myfunc
echo "The temp from outside is $tmp"
Output
285
Problem-D Solution
Pseudocode
The following script will recurse a number until it is less than 5 and will stop
executing when the number reaches the value 5.
Use the declare command to decide the base case for the recursion, i.e.,
counter=0
define the function name()
{
increment the counter
define the condition (counter less than 5) inside the if statement
then
display the value of the counter
invoke the function
fi
}
invoke the function
286
Flowchart
Script
declare -i counter=0
script_recurse()
{
((counter++))
if [ $counter -lt 5 ]
then
echo $counter
script_recurse
fi
}
script_recurse
287
Output
Exercise:
Below are some additional examples for your practice, which will help bring
further clarity about iterations.
288
#!/bin/bash
class_function () {
echo "class average"
return 55
}
class_function
echo $?
Exercise C: Use function in a Bash program to allow the user to enter two
numbers and print their sum.
#!/bin/bash
func_addition(){
sum=$(($1+$2))
return $sum
}
read -p "Enter a number: " inp1
read -p "Enter a number: " inp2
add $inp1 $inp2
echo "The result is : " $?
Final Words
In this chapter, we have covered the various types of functions that you, as an
aspiring Bash programmer, must be aware of before writing meaningful scripts
containing functions. These well-explained examples will help students gain
289
290
References
291
Chapter 19
“
Writing a Bash script is not only about performing arithmetic operations or
building recursive scripts. In advance Bash scripting, file handling plays a
crucial role in completing administrative tasks. This chapter discusses some file
handling and directory commands.
We have covered a long way in learning Bash scripting. In the previous chapters,
we covered the basics and conditional operators. Then, we moved to the
intermediate level and learned about functions and iterations in Bash scripts. Next
in the ladder comes advanced scripting, which involves learning about
administrative and file handling commands. What if you wrote a script and wanted
to locate it quickly? Or you wanted to change its contents without opening it? We
cover these topics in this chapter, addressing various file handling operations in
GitBash.
Read a File
Suppose you have a file named carcompany.txt, which includes the following
content:
Audi
292
Volkswagen
Mercedes
BMW
Hyundai
To read carcompany.txt line by line without using the cat command, you need
to run the following command:
The while loop in the above command will read from the file carcompany.txt
line by line and store it in the $line variable. It will print the content later.
You can write the following code to read the contents of carcompany.txt.
#!/bin/bash
file_name='carcompany.txt'
293
The $file_name variable will store the existing filename, and the $n
variable will maintain the value of the line number. The output of the above
script:
If you run the carcompany.txt file with the cat command, the terminal will
display its original content.
You can create a new directory in Git Bash by using a simple command. It is
the same command used in Linux systems too. To create a new directory in Git
Bash:
294
Now that we have created a folder successfully, we must know how to view the
folder inside the working directory. Following are the steps to view all
directories:
• Navigate to the working directory (Bashtutorial)
• Type the command Is.
• Press enter. You can now see all the directories.
• If your directory contains hidden folders, you need to use the command
Is -a.
Remove a directory
In the previous example, we needed to create only one folder with the name
'Sample Folder,' but the Is command shows two folders. So how to delete the
extra folder. Simply write the rmdir <filename> command. The example
is shown below. To create the required folder, we need to enclose the sample
folder in quotation marks.
295
Write to a File
Whenever you run a command in the Bash shell, it prints the command's output to
the terminal, and you can read it immediately. However, you can also redirect it to
a Log file from where you can review it later. You can either use the > (right angle
bracket sign) or >> (double right-angle sign).
a) > (right angle bracket sign): It is used for writing the command output to a
disk file. It will create a file if there is no file with the name you specified.
However, if the specified filename is present, it will overwrite its contents.
b) >> (double right-angle sign): It is used for writing the command output to a
file and then appends the output to the file's existing contents. It will create
a new file if the one with the specified name is not present.
Technically, both the > and >> operators redirect the standard output (stdout) to a
file. Here are the instructions for when to use these operators:
• When you are writing the file the first time and want the file to be fresh,
without any previous data, use the > sign. It will overwrite any previous data
in the file.
• You can further use the >> sign for appending the data to a file.
For example, We will use the Is command in conjunction with the > sign. Instead
of printing the complete file and folders list to the screen, the Is command, coupled
with > will save the output on the specified file name.
Bash Script
296
#!/bin/bash
output=output_file.txt
ls > $output
[edit or gedit] output_file.txt
Output:
As seen above, the Is command redirects the output into a file. For printing the
file's contents to the terminal, you can use the cat command as shown below:
Bash Script
#!/bin/bash
output=output_file.txt
ls > $output
cat $output
Output
297
If you don't want to delete the available data in a file but want to redirect multiple
command outputs to it, then use the >> operator. In the following example, we will
append the system information in the specified file.
Bash Script
#!/bin/bash
output=output_file.txt
ls > $output
uname -a >> $output
[edit or gedit] output_file.txt
Output
298
You can repeat the process multiple times for appending the output towards the
file's end.
Append to a File
We have already seen how to use >> operator to append a file. Another way to
append to a file is by using the tee command. The tee command can be used to
both read from the standard input and write to the standard output and multiple
files simultaneously.
• The tee command will overwrite the specified file by default. For appending
the output to the specified file, you can use -a(--append) with tee:
299
The advantage that the tee command has over >> operator is that it allows users
to append to multiple files.
Update a File
Bash offers you the ability to edit files without opening them. You can use the sed
command to find and replace text in the file.
Syntax:
Example:
Consider the following text file as input.
300
• If you want to replace or substitute a string in the above file, use the sed
command. Replace unix with linux:
"s" will specify the substitution operation and / are delimiters. "Unix"
refers to the search pattern, and the replacement string is "Linux".
Output
linux is super easy to learn and unix is a multiuser os. Learn unix because
unix is powerful.
The key point to note here is that the sed command will only replace the
pattern's first occurrence in every line and not the subsequent occurrences.
• Copying files
System administrators need to regularly copy files and directories from one
location to another in the filesystem. They can use the cp command to
achieve this smoothly. It will use two parameters in its basic form: the
source and destination object. The syntax is as follows:
301
cp source destination
• Renaming files
In a Bash script, renaming files is also called moving. You can use the mv
command to move files and directories from one location to another.
Moving the file will change its filename, but the timestamp value and inode
number will remain the same.
Exercise:
Exercise A: Write a bash script to track the number of times the current script
is executed. Use an external file to keep the number (Hint: You need to ensure
that you can write to and read from the file)
Exercise B: Write a bash script to copy the text files (.txt extensions) in the
current directory to a subdirectory called textDir in the current folder. Your
script should create the textDir if the directory doesn’t exist.
302
Exercise A Solution:
Before wring the script, you need to create a file and the
initial number in the file and save it.
#!/bin/bash
COUNTER_FILE="counter.txt"
count=`cat $COUNTER_FILE`
((count++))
echo $count > $COUNTER_FILE
echo $count;
Exercise B Solution:
#!/bin/bash
if [ ! -d "textDir" ]
then
echo "Directory doesn't exist. Creating now"
mkdir "textDir"
echo "Directory created"
fi
echo "Moving text files to TextDir"
mv *.txt textDir
Final Words
Thus, we have seen the basic file handling and directory commands in this chapter.
These commands are inclined towards the advanced side and are easy to grasp
once the student has completed the basic and intermediate chapters.
303
References
1. Fahmida Yesmin, "How to read file line by line in Bash script", from:
https://linuxhint.com/read_file_line_by_line_bash/
304
Chapter 20
“
In the previous chapter, we saw how different file handling commands could
help users perform complex administrative and file editing tasks with ease. This
chapter will cement our knowledge of the file handling commands by solving
some interesting questions related to file handling in Bash
You will often encounter situations where you will need to use the file
handling commands. It can either be checking if a file exists or not, create a
new directory, move files to different folders, or delete files. The bash shell
offers you the option to use various commands to manipulate the file system.
The most crucial file handling command is mkdir, which is used for creating
new directories. The mv command helps in situations where you need to move
multiple files to a new directory. Additionally, if you have created a wrong file
or delete a particular file to free up disk space, the rm command comes in
handy. We discuss these essential file handling commands in this chapter, with
detailed discussions, pseudocodes, and flowcharts for a deeper understanding of
the topic.
305
Practice Problems
Problem-A
You have downloaded many of your favourite instrumental songs from the
internet, and now you want to save them in a new directory. Write a Bash script
demonstrating how you can create a new parent directory
• The current working directory in Bash is the one from where you will run
the commands.
• According to the problem, you need to create a new directory in the
directory "music"
• You will need to provide the relative or absolute path to the parent directory
if you need to create a directory in a separate location.
• In this case, you need to create a new directory in "music"
• Thus, you will write:
mkdir music/newdir
• You will get the error "Permission denied" if you try to create the directory
in the parent directory where you don't have permission to create a file.
• In Bash, the parent directory is the one that is above other directories in the
directory tree.
• To create the directory mentioned in the question, write:
mkdir music/instrumental/best
• If any of the above-mentioned parent directories don't exist, you will get an
error:
306
Problem-B
You are running a teaching institute and want to organize the teaching
content according to various courses. Write a Bash script to create a folder
structure for the lessons taught in your institute: Science, Maths, Applied
Mathematics, English, and Social Science. Each folder must contain sub-folder
named slides, observations, notes, past papers.
• We will create the directories (folders) using the mkdir -p command already
discussed in the previous example.
• Use your favourite editor to create the file by the name of
coursematerial.bash
307
Problem-C
It's Binge-watch season, and you are downloading the episodes of your
favourite shows Gotham and Arrow and saving them to the "downloads" folder.
Write a Bash script that will run when the downloads complete, look for specific
file names in the "downloads" folder and move them to a different directory based
on the file name.
• We will use the mv command, which is short for move, to solve the above
problem. It is used for renaming and moving files from one location to
another. Its syntax is:
mv [OPTIONS] SOURCE DESTINATION
• The SOURCE will represent one or multiple files/directories.
• DESTINATION will represent a single file/directory.
• If you give multiple files or directories as the SOURCE, you must specify a
directory as the destination. We are moving multiple files from the
"downloads" folder to the specified directory in our problem.
308
• If you specify single files for both SOURCE and DESTINATION, then the
script will rename the file.
• If the DESTINATION is non-existent and you specify SOURCE as a
directory, the script will rename the SOURCE to DESTINATION. If the
DESTINATION exists, the SOURCE will be moved inside it.
• A crucial point to consider is that you must have write permissions for
SOURCE and DESTINATION; otherwise, you will get a permission denied
error.
• We need to move files in the downloads folder to the TVshows/ folder.
• First, we will use the cd command to change the working directory to
downloads.
• We will then use the for loop and invoke the mv command to move each file
("$filename") to its respective episode directory.
• It is crucial to include the / after destination. If the script detects that the
destination directory doesn't exist (because of misspelling), it will create the
directory as a file.
Problem-D
• We have learned in the earlier chapter that the rm command helps us remove
any file. So, we will use the rm command to delete the file.
309
Problem-A Solution
Pseudocode
Start
End
Flowchart
310
Bash Script
#!/bin/bash
cd "/home/e”
#Replace /home/e with music parent directory."
mkdir -p music/instrumental/best
Output
311
Problem-B Solution
Pseudocode
Start
- Invoke the mkdir command with -p. (Use commas to separate the
folder names and / to separate the list of subfolders within the created
directories)
End
Flowchart
Bash Script
#!/bin/bash
312
mkdir -p
{Science,Maths,Applied_Mathematics,English,Social_S
cience}/{Slides,Observations,Notes,Past_papers}
Output
Problem-C Solution
Pseudocode
313
Start
End
Flowchart
314
Bash Script
#!/bin/bash
cd "$home/Downloads"
#Replace $home with Downloads and TVShows parent
directory."
#!/bin/bash
for file_name in *;
do
case "${filename,,*}" in
gotham*) mv "$file_name"
"$home/TVshows/gotham/" ;;
esac
done
Output
315
Problem-D Solution
Pseudocode
Start
End
Flowchart
316
Bash Script
#!/bin/bash
echo "Enter the filename to remove"
read filename
rm -i $filename
Output
317
Problems to Solve
1) Write a code to check whether a given directory exists before using the mkdir
command to create a new directory. (hint: use the -d command)
3) Use the file test operator (-f) to check if a file exists or not. (Hint: input the file
name from the command line)
318
Solutions
Q1-Solutions
#!/bin/bash
echo "Enter the directory name"
read name_dir
if [ -d "$name_dir" ]
then
echo "Directory exists"
else
`mkdir $name_dir`
echo "Directory is created"
fi
Run check_directory.sh from the command line, and you will get the
following output.
Q2-Solutions
319
#!/bin/bash
value=$(<Learning_Bash.txt)
echo "$value"
Run read_text.sh from the command line, and you will get the following
output.
Q3-Solutions
#!/bin/bash
file_name=$1
if [ -f "$file_name" ]; then
echo "File exists"
else
echo "File does not exist"
fi
Run file_exist.sh from the command line, followed by the file name you
want to search, and you will get the following output.
320
Final Words
We have dwelled upon the various file handling commands which you can use to
manipulate the file system. The interesting examples with detailed discussions and
graphically illustrative flowcharts will surely make learning these commands a fun
experience.
321
References
2. Pietro, "Create multiple folders and subfolders from bash script" from:
https://pietropassarelli.com/bash_script.html
3. Stack Overflow, "SH script to move files from one dir to another depending
on the filename" from:
https://stackoverflow.com/questions/7573815/sh-script-to-move-files-from-
one-dir-to-another-depending-on-the-filename
4. Ask Ubuntu, "How to make a shell script to move files to individual folders
based on the filename?" from:
https://askubuntu.com/questions/1188803/how-to-make-a-shell-script-to-
move-files-to-individual-folders-based-on-the-file
322