Operating System Question With Answers
Operating System Question With Answers
--> Below are mentioned some of the most crucial and notable
characteristics of the operating system:
Work Management
One of the important characteristics of the operating system is
task management. It is also considered an important OS
function as it controls all the activities related to handling tasks
systematically. In summary, the OS determines the order in
which the activities are carried out, with a queue indicating the
jobs that await execution. Work management is the key to
controlling all tasks and their required resources without any
conflicts. It helps streamline processes to better schedule tasks
and effectively manage resources without compromising
performance.
Resource Management:
The hardware and software of a computer are closely
interconnected. Each of the two does not work without the
other. As a result, the operating system balances these two
resources. OS examines all tasks systematically and verifies if all
computer components are operational. All executing tasks
require resources for their execution. Ensuring they are allotted
the required resources is also an important characteristic of the
operating system.
Multitasking System:
Multitasking is now a standard feature of current operating
systems. They are capable of performing numerous jobs at
once. For example, if a user is working in Excel and wants to
print a page, he does not need to interrupt his work. With just
one command, the page will be printed, and the user can access
the drives without having to close the tab. As a result,
multitasking is one of the best characteristics of operating
systems.
Associated mechanism:
The following critical mechanisms also highlight some
characteristics of Operating systems:
It has a system to validate each user, which can include
password protection or other features.
It also protects against dangerous components by blocking
them before they reach the device. Many malware and
malicious software are currently affecting computer gadgets. As
a result, having this mechanism in the operating system is
critical.
Most operating systems also have a method for limiting the
number of resources available to each user. As a result, if the
boss has to give his employee access to his computer, he can
restrict access to specific files.
User can view the logical User can never view physical
Visibility address of a program. address of program.
segmentation.
15. The size of the page needs There is no constraint on the size of
S.NO Paging Segmentation
It is of five types:
1. Paging
2. Multilevel Paging
It is of two types:
3. Inverted Paging
1. Fixed(or static) partitioning 4. Segmentation
9. 2. Dynamic partitioning 5. Segmented Paging
In this scheme, User can load the bigger size processes than the available main memory
by having the illusion that the memory is available to load the process.
Instead of loading one big process in the main memory, the Operating System loads the
different parts of more than one process in the main memory.
By doing this, the degree of multiprogramming will be increased and therefore, the CPU
utilization will also be increased.
Play Video
Since all this procedure happens automatically, therefore it makes the computer feel like
it is having the unlimited RAM.
A page is copied to the main memory when its demand is made or page fault occurs.
There are various page replacement algorithms which are used to determine the pages
which will be replaced. We will discuss each one of them later in detail.
1. The computer's hardware track to the kernel and the program counter is often saved on
the stack. The CPU registers hold information about the current state of instruction.
2. An assembly program is started, which saves the general registers and other volatile data
to prevent the Operating system from destroying it.
Play Video
Now, let's understand the procedure of page fault handling in the OS:
1. Firstly, an internal table for this process to assess whether the reference was valid or
invalid memory access.
2. If the reference becomes invalid, the system process would be terminated. Otherwise, the
page will be paged in.
3. After that, the free-frame list finds the free frame in the system.
4. Now, the disk operation would be scheduled to get the required page from the disk.
5. When the I/O operation is completed, the process's page table will be updated with a
new frame number, and the invalid bit will be changed. Now, it is a valid page reference.
6. If any page fault is found, restart these steps from starting.
a) FIFO. b) LRU.
--> Page Replacement Algorithms:
1. First In First Out (FIFO): This is the simplest page replacement algorithm. In this
algorithm, the operating system keeps track of all pages in the memory in a queue, the
oldest page is in the front of the queue. When a page needs to be replaced page in the
front of the queue is selected for removal.
Example 1: Consider page reference string 1, 3, 0, 3, 5, 6, 3 with 3 page frames.Find the
number of page faults.
Initially, all slots are empty, so when 1, 3, 0 came they are allocated to the empty slots —
> 3 Page Faults.
when 3 comes, it is already in memory so —> 0 Page Faults. Then 5 comes, it is not
available in memory so it replaces the oldest page slot i.e 1. —>1 Page Fault. 6 comes, it
is also not available in memory so it replaces the oldest page slot i.e 3 —>1 Page
Fault. Finally, when 3 come it is not available so it replaces 0 1 page fault.
Belady’s anomaly proves that it is possible to have more page faults when increasing the
number of page frames while using the First in First Out (FIFO) page replacement
algorithm. For example, if we consider reference strings 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4,
and 3 slots, we get 9 total page faults, but if we increase slots to 4, we get 10-page faults.
2. Optimal Page replacement: In this algorithm, pages are replaced which would not be
used for the longest duration of time in the future.
Example-2: Consider the page references 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 3 with 4 page
frame. Find number of page fault.
Initially, all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page
faults
0 is already there so —> 0 Page fault. when 3 came it will take the place of 7 because it is
not used for the longest duration of time in the future.—>1 Page fault. 0 is already there
so —> 0 Page fault. 4 will takes place of 1 —> 1 Page Fault.
Now for the further page reference string —> 0 Page fault because they are already
available in the memory.
Optimal page replacement is perfect, but not possible in practice as the operating system
cannot know future requests. The use of Optimal Page replacement is to set up a
benchmark so that other replacement algorithms can be analyzed against it.
3. Least Recently Used: In this algorithm, page will be replaced which is least recently
used.
Example-3: Consider the page reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 3 with 4
page frames. Find number of page faults.
Initially, all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page
faults
0 is already their so —> 0 Page fault. when 3 came it will take the place of 7 because it is
least recently used —>1 Page fault
0 is already in memory so —> 0 Page fault.
4 will takes place of 1 —> 1 Page Fault
Now for the further page reference string —> 0 Page fault because they are already
available in the memory.
1. Most Recently Used (MRU): In this algorithm, page will be replaced which has
been used recently. Belady’s anomaly can occur in this algorithm.
8.Consider the following page reference using three frames that are initially
empty. Find the page faults using FIFO algorithm, where the page reference
sequence: 7,0,1, 2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1?
9. Consider the following page reference using three frames that are initially
empty. Find the page faults using LRU algorithm, where the page reference
sequence: 7,0,1, 2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1?
10. Define (1) Cooperating process:
There are various processes in a computer system, which can be either independent or
cooperating processes that operate in the operating system. It is considered
independent when any other processes operating on the system may not impact a
process. Process-independent processes don't share any data with other processes. On
the other way, a collaborating process may be affected by any other process executing
on the system. A cooperating process shares data with another.
(2) Independent process:The process that does not affect or is affected by the
other process while its execution then the process is called Independent Process.
Example The process that does not share any shared variable, database, files,
etc.
(3) Race condition: When more than one process is executing the same code
or accessing the same memory or any shared variable in that condition there
is a possibility that the output or the value of the shared variable is wrong so
for that all the processes doing the race to say that my output is correct this
condition known as a race condition. Several processes access and process
the manipulations over the same data concurrently, then the outcome
depends on the particular order in which the access takes place. A race
condition is a situation that may occur inside a critical section. This happens
when the result of multiple thread execution in the critical section differs
according to the order in which the threads execute. Race conditions in
critical sections can be avoided if the critical section is treated as an atomic
instruction. Also, proper thread synchronization using locks or atomic
variables can prevent race conditions
(4) Critical section: A critical section is a code segment that can be accessed by
only one process at a time. The critical section contains shared variables that
need to be synchronized to maintain the consistency of data variables. So the
critical section problem means designing a way for cooperative processes to
access shared resources without creating data inconsistencies.
In the entry section, the process requests for entry in the Critical Section.
Any solution to the critical section problem must satisfy three requirements:
Preemptive Scheduling
In Preemptive Scheduling, the tasks are mostly assigned with their priorities.
Sometimes it is important to run a task with a higher priority before another
lower priority task, even if the lower priority task is still running. The lower
priority task holds for some time and resumes when the higher priority task
finishes its execution.
Non-Preemptive Scheduling
In this type of scheduling method, the CPU has been allocated to a specific
process. The process that keeps the CPU busy will release the CPU either by
switching context or terminating. It is the only method that can be used for
various hardware platforms. That’s because it doesn’t need special hardware
(for example, a timer) like preemptive scheduling.
Deadlock Prevention
We can prevent Deadlock by eliminating any of the above four conditions.
2. The process will make a new request for resources after releasing the
current set of resources. This solution may lead to starvation.
Eliminate No Preemption
Preempt resources from the process when resources required by other high
priority processes.
Deadlock Avoidance
Deadlock avoidance can be done with Banker’s Algorithm.
Banker’s Algorithm
Bankers’s Algorithm is resource allocation and deadlock avoidance algorithm
which test all the request made by processes for resources, it checks for the
safe state, if after granting request system remains in the safe state it allows the
request and if there is no safe state it doesn’t allow the request made by the
process.
Inputs to Banker’s Algorithm:
--> n operating systems, to improve the performance of more than one CPU can be
used within one computer system called Multiprocessor operating system.
Multiple CPUs are interconnected so that a job can be divided among them for faster
execution. When a job finishes, results from all CPUs are collected and compiled to give
the final output. Jobs needed to share main memory and they may also share other
system resources among themselves. Multiple CPUs can also be used to run multiple
jobs simultaneously.
For Example: UNIX Operating system is one of the most widely used multiprocessing
systems.
o These systems are fault-tolerant. Failure of a few processors does not bring the entire
system to a halt.
Disadvantages of Symmetrical multiprocessing operating system:
Further, one processor may act as a master processor or supervisor processor while
others are treated as shown below.
In the above figure, the asymmetric processing system shows that CPU n1 acts as a
supervisor whose function controls other following processors.
In this type of system, each processor is assigned a specific task, and there is a
designated master processor that controls the activities of other processors.
For example, we have a math co-processor that can handle mathematical jobs better
than the main CPU. Similarly, we have an MMX processor that is built to handle
multimedia-related jobs. Similarly, we have a graphics processor to handle the graphics-
related job better than the main processor. When a user submits a new job, the OS has
to decide which processor can perform it better, and then that processor is assigned
that newly arrived job. This processor acts as the master and controls the system. All
other processors look for masters for instructions or have predefined tasks. It is the
responsibility of the master to allocate work to other processors.
Mapping:
The basic characteristics of cache memory are its fast access time. So, it is very little or
no time must be wasted when searching for words in the cache. The transformation of
data from main memory to cache memory is referred to as a ‘Mapping‘ process. There
are 3 types of mapping procedures are there for cache memory:
1. Associative Mapping
2. Direct Mapping
3. Set-Associative Mapping
Associative Mapping:
The associative memory stores both the address and the content (data) of the memory
word. This permits any location in the cache to store any word from the main memory.
Direct Mapping:
In this mapping procedure, the CPU address of 15 bits is divided into two fields. One is
the index field of 9 bits and the second is a tag equal to 6 bits. The number of bits in the
index field is equal to the number of address bits required to access the cache memory.
Set-Associative Mapping:
The third type of cache organization is called set-associative mapping. In this mapping,
each word of the cache can store two or more words of memory under the same index
address. Each data word is stored together with its tag and the number of tag data
items in one word of cache is said to form a set.
Cache Design:
The design of the cache depends on 5 factors. These are:
i. Cache Size: The small caches can have a significant impact on performance. If the
size increases the performance will decrease.
ii. Block Size: The block size is the unit of data exchanged between the cache and main
memory. As the block size increases, ‘more unuseful data is brought into the cache.
The hit ratio will begin to decrease.
iii. Mapping Function: The transformation of data from main memory to cache memory
is referred to as a mapping process. The mapping function determines which location the
block will occupy.
iv. Replacement Algorithm: This factor determines which block is replace. If the cache is
full. We would like to replace a block that is least likely to be needed again shortly.
v. Write Policy: The write policy dictates when the memory write operation takes place.
2. Bada
Samsung is the launcher of this operating system. It came into market
in 2010. Moreover, it includes features like 3-D graphics, application
installation, multipoint touch etc.
3. Blackberry OS
The developer of this operating system is Reasearch In Motion (RIM).
It was specifically designed for blackberry devices. Furthermore, it is
useful for corporate users.
4. Apple iOS
After android, it is one of the most popular OS. It is designed to run on
Apple devices such as iPhones, iPad tablets, etc. Moreover, like the
android devices have the playstore for apps download. Likewise, apple
iOS contains the app store. Also, it has very strong security features.
7. Harmony OS
It is a latest OS moreover, Huawei is its developer. It is specifically
designed for use in IoT devices.
8. Palm OS
Its other name is Garnet OS. Furthermore, Palm Ltd. is its developer
which developed this OS for use in Personal Digital Assisstants
(PADs).
9. WebOS
Palm Ltd is its developer. Moreover, it is based on Linux kernel
and HP uses it in its mobile devices and touchpads.
In Hard RTOS, all critical tasks must be completed within the specified time duration, i.e.,
within the given deadline. Not meeting the deadline would result in critical failures such
as damage to equipment or even loss of human life.
For Example,
Let's take an example of airbags provided by carmakers along with a handle in the
driver's seat. When the driver applies brakes at a particular instance, the airbags grow
and prevent the driver's head from hitting the handle. Had there been some delay even
of milliseconds, then it would have resulted in an accident.
Soft RTOS accepts a few delays via the means of the Operating system. In this kind of
RTOS, there may be a closing date assigned for a particular job, but a delay for a small
amount of time is acceptable. So, cut off dates are treated softly via means of this kind
of RTOS.
For Example,
This type of system is used in Online Transaction systems and Livestock price quotation
Systems.
In Firm RTOS additionally want to observe the deadlines. However, lacking a closing
date might not have a massive effect, however may want to purposely undesired effects,
like a massive discount within the fine of a product.
Applications of Real Time Operating System Real-time systems are used in:
Used in any system that provides up to date and minute information on stock
prices.
Internet Telephony.
Heart Pacemaker.
Components of RTOS The Scheduler: This component of RTOS tells that in which order, the
tasks can be executed which is generally based on the priority. Symmetric Multiprocessing
(SMP): It is a number of multiple different tasks that can be handled by the RTOS so that
parallel processing can be done. Function Library: It is an important element of RTOS that acts
as an interface that helps you to connect kernel and application code. This application allows
you to send the requests to the Kernel using a function library so that the application can give
the desired results
Shell script is a list of commands in a computer program that is run by the Unix shell which is a
command line interpreter. A shell script usually has comments that describe the steps. The different
operations performed by shell scripts are program execution, file manipulation and text printing. A
wrapper is also a kind of shell script that creates the program environment, runs the program etc.
Types of Shells
Bourne Shell :This is the default shell for version 7 Unix. The character $ is the default prompt for the
bourne shell. The different subcategories in this shell are Korn shell, Bourne Again shell, POSIX shell etc.
C Shell :This is a Unix shell and a command processor that is run in a text window. The character % is the
default prompt for the C shell. File commands can also be read easily by the C shell, which is known as a
script.
Batch jobs :
Several commands that would be entered manually in a command line interface can be executed
automatically using a shell script. This can be done without the user needing to trigger each command
separately.
Programming
There are many features in modern shell scripts that are only found in sophisticated programming
languages such as arrays, variables, comments etc. Many complicated applications can be written in
shell scripts using these features. But there is a problem i.e. shell script languages don’t support classes,
threading etc.
Generalisation:
It is much more flexible to use loops, variables etc for multiple tasks in shell script. An example of this is
a Unix shell script known as bash, which converts jpg images to png images.
Shortcuts:
There is a shortcut provided by a shell script for a system command where command options,
environment settings or post processing apply. This still allows the shortcut script to act as a Unix
command.
1. The commands and syntax of the shell script are the same as that entered at the command line.
Because of this, there is no need to switch to a completely different syntax.
2.It is much faster to write a code in shell script than in other programming languages. This also means
that the program is easier to create and files required can be selected easily.
3.Shell script can also be used to provide linkage for already existing programs.
4. Shell scripting can be used by users that are not experts to modify and tailor the behaviour of their
programs according to their requirements.
2.The programs in shell script are quite slow while executing and a new process is required for every
shell command executed.
-->
VPS
40 Essential Linux
Commands That Every User
Should Know
Linux is a family of open-source Unix operating systems based on the
Linux Kernel. They include Ubuntu, Fedora, Debian, openSUSE, and Red
Hat. Using Linux to manage a Virtual Private Server (VPS) is common
practice.
When operating Linux, you need to use a shell – a program that gives you
access to the operating system’s services. Most Linux distributions use a
graphical user interface (GUI), making them beginner-friendly.
However, we recommend utilizing the command-line interface (CLI)
because it’s quicker and offers more control. Tasks that require multiple
steps on the GUI can be done in a matter of seconds by entering
commands into the CLI.
So if you want to use Linux, learning the common utilities or commands will
go a long way. This article will discuss the 40 basic commands to help you
use your Linux distro effectively.
o What Is a Linux Command?
o The 40 Most Commonly Used Linux Commands
o Bonus Tips and Tricks
o Download a Free Linux Commands Cheat Sheet
o Linux Commands FAQ
o What Is the Basic Command of Linux?
o How Many Commands Does Linux Have?
2. pwd command
Use the pwd command to find the path of your current working directory.
Simply entering pwd will return the full current path – a path of all the
directories that starts with a forward slash (/). For
example, /home/username.
The pwd command uses the following syntax:
pwd [option]
It has two acceptable options:
3. cd command
To navigate through the Linux files and directories, use the cd command.
Depending on your current working directory, it requires either the full path
or the directory name.
Running this command without an option will take you to the home folder.
Keep in mind that only users with sudo privileges can execute it.
Let’s say you’re in /home/username/Documents and want to go
to Photos, a subdirectory of Documents. To do so, enter the following
command:
cd Photos.
If you want to switch to a completely new directory, for
example, /home/username/Movies, you have to enter cd followed by the
directory’s absolute path:
cd /home/username/Movies
Here are some shortcuts to help you navigate:
4. ls command
The ls command lists files and directories within a system. Running it
without a flag or parameter will show the current working directory’s
content.
To see other directories’ content, type ls followed by the desired path. For
example, to view files in the Documents folder, enter:
ls /home/username/Documents
Here are some options you can use with the ls command:
• ls -R lists all the files in the subdirectories.
• ls -a shows hidden files in addition to the visible ones.
• ls -lh shows the file sizes in easily readable formats, such as MB,
GB, and TB.
5. cat command
Concatenate, or cat, is one of the most frequently used Linux commands.
It lists, combines, and writes file content to the standard output. To run the
cat command, type cat followed by the file name and its extension. For
instance:
cat filename.txt.
Here are other ways to use the cat command:
6. cp command
Use the cp command to copy files or directories and their content. Take a
look at the following use cases.
To copy one file from the current directory to another, enter cp followed by
the file name and the destination directory. For example:
cp filename.txt /home/username/Documents
To copy files to a directory, enter the file names followed by the destination
directory:
cp filename1.txt filename2.txt filename3.txt
/home/username/Documents
To copy the content of a file to a new file in the same directory,
enter cp followed by the source file and the destination file:
cp filename1.txt filename2.txt
To copy an entire directory, pass the -R flag before typing the source
directory, followed by the destination directory:
cp -R /home/username/Documents
/home/username/Documents_backup
7. mv command
The primary use of the mv command is to move and rename files and
directories. Additionally, it doesn’t produce an output upon execution.
Simply type mv followed by the filename and the destination directory. For
example, you want to move filename.txt to
the /home/username/Documents directory:
mv filename.txt /home/username/Documents.
You can also use the mv command to rename a file:
mv old_filename.txt new_filename.txt
8. mkdir command
Use the mkdir command to create one or multiple directories at once and
set permissions for each of them. The user executing this command must
have the privilege to make a new folder in the parent directory, or they may
receive a permission denied error.
Here’s the basic syntax:
mkdir [option] directory_name
For example, you want to create a directory called Music:
mkdir Music
To make a new directory called Songs inside Music, use this command:
mkdir Music/Songs
The mkdir command accepts many options, such as:
• -p or –parents create a directory between two existing folders. For
example, mkdir -p Music/2020/Songs will make the new “2020”
directory.
• -m sets the file permissions. For instance, to create a directory with
full read, write, and execute permissions for all users, enter mkdir -
m777 directory_name.
• -v prints a message for each created directory.
9. rmdir command
To permanently delete an empty directory, use the rmdir command.
Remember that the user running this command should
have sudo privileges in the parent directory.
For example, you want to remove an empty subdirectory
named personal1 and its main folder mydir:
rmdir -p mydir/personal1
10. rm command
The rm command is used to delete files within a directory. Make sure that
the user performing this command has write permissions.
Remember the directory’s location as this will remove the file(s) and you
can’t undo it.
Here’s the general syntax:
rm filename
To remove multiple files, enter the following command:
rm filename1 filename2 filename3
Here are some acceptable options you can add:
15. df command
Use the df command to report the system’s disk space usage, shown in
percentage and kilobyte (KB). Here’s the general syntax:
df [options] [file]
For example, enter the following command if you want to see the current
directory’s system disk space usage in a human-readable format:
df -h
These are some acceptable options to use:
16. du command
If you want to check how much space a file or a directory takes up, use
the du command. You can run this command to identify which part of the
system uses the storage excessively.
Remember, you must specify the directory path when using
the du command. For example, to check /home/user/Documents enter:
du /home/user/Documents
Adding a flag to the du command will modify the operation, such as:
• -x extracts a file.
• -t lists the content of a file.
• -u archives and adds to an existing archive file.
Check out the more practical examples to know more about the other
functions.
• The Kernel is the heart of your operating system. Kernel handles all operations on behalf
of operating system.
• A Kernel is an intermediary between applications and hardware. This means that applications
can run without knowing or caring about the underlying hardware details. It manages low-
level tasks such as disk management, task management, and memory management.
Whenever you start a system, Kernel is the first program that is loaded after the bootloader,
and it remains in the memory until the operating system is shut-down.
•
• The core component keeps your system running, managing all your software and hardware.
Without it, your computer would be a useless pile of metal and plastic.
• A kernel must be fast and responsive. It needs to handle all the requests and responses
quickly and efficiently. To do this, the Kernel uses a lot of kernel-level memory. This
memory is isolated from the main memory of your computer. This means that the Kernel can
use it to store data and code without affecting other applications.
• Monolithic Kernel
• Microkernel
• Hybrid Kernel
• Nano Kernel
• Exo Kernel
• Monolithic Kernel: Monolithic kernels are the simplest and most common type of Kernel. They
include the core functionality of the operating system and support all devices connected to it. In
this, the user and kernel services are implemented in the same memory space. Due to this, the size
of the kernel increases, which in turn increases the size of the operating system. The main benefit
is that the process execution is faster as there is no separate memory space for the user and Kernel.
• Microkernel: Microkernels are a newer development and, as such, are not as common as
monolithic kernels. They include only the essential services and devices required for the system to
function. This results in a smaller kernel that is faster and uses less memory. Here, the user and
kernel services are implemented in two different spaces. It has separate User Space and Kernel
Space. This reduces the size of the Kernel and results in reducing the size of the operating system.
• Hybrid Kernel: Hybrid kernels combine monolithic and microkernels. They include more
services than microkernels but less than monolithic kernels. This allows them to offer some of the
benefits of both kernels. It borrows speed from the monolithic kernels and modularity from
microkernels.
• Nano Kernel: Nano kernels are the smallest type of Kernel, consisting of only a few thousand
lines of code. It means that the code executing in the privileged mode of the hardware is minimal.
They are used primarily in embedded systems or devices with limited resources.
• Exo Kernel: This Kernel has separate resource protection and management. It is suitable for use
when performing application-specific customization. Exo kernels are designed for use in mobile
devices. They are a variation of microkernels that include additional features specifically for
mobile devices, such as power management and support for multiple processors.
1. while statement
2. for statement
3. until statement
To alter the flow of loop statements, two commands are used they are,
1. break
2. continue
Their descriptions and syntax are as follows:
• while statement
Here command is evaluated and based on the result loop will executed, if
command raise to false then loop will be terminated
Syntax
•
• for statement
The for loop operate on lists of items. It repeats a set of commands for every
item in a list.
Here var is the name of a variable and word1 to wordN are sequences of
characters separated by spaces (words). Each time the for loop executes,
the value of the variable var is set to the next word in the list of words, word1
to wordN.
Syntax
•
• until statement
The until loop is executed as many as times the condition/command
evaluates to false. The loop terminates when the condition/command
becomes true.
Syntax
•
Example Programs
Example 1:
Implementing for loop with break statement
• php
for a in 1 2 3 4 5 6 7 8 9 10
do
if [ $a == 5 ]
then
break
fi
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Example 2:
Implementing for loop with continue statement
• php
for a in 1 2 3 4 5 6 7 8 9 10
do
if [ $a == 5 ]
then
continue
fi
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10
Example 3:
Implementing while loop
• php
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
Example 4:
Implementing until loop
• php
a=0
this post, we will write a shell script to reverse a number which is given as the input. INPUT: line 1:
number OUTPUT: Print a single number which is the reverse of the given number The following is the
shell script to reverse a number which is given as the input:
echo enter n
read n
num=0
while [ $n -gt 0 ]
do
num=$(expr $num \* 10)
k=$(expr $n % 10)
n=$(expr $n / 10)