0% found this document useful (0 votes)
132 views

OS Practical File Final

operating system study notes of bca 3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views

OS Practical File Final

operating system study notes of bca 3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Ques 1. Installation of windows OS.

Installing Windows via a bootable USB offers convenience and flexibility,


especially when performing a clean installation or upgrading to a newer
version. This method ensures a smooth and efficient installation process while
minimizing potential errors.

Before diving into the installation steps, it's crucial to emphasize the
importance of backing up your data. While the installation process typically
preserves existing files during an upgrade, a clean installation involves wiping
the drive, erasing all data. Therefore, creating a backup ensures you can
restore essential files and settings if needed.

Once you've prepared your USB bootable device and adjusted the boot order
in your computer's BIOS settings, you're ready to initiate the Windows
installation process. Follow these detailed steps to ensure a successful
installation:

1. Preparation and Booting:

● Insert the bootable USB into a USB port on your computer.


● Power on your computer and access the BIOS settings by
pressing the designated key during startup (common keys include
F2, F12, Del).
● In the BIOS settings, navigate to the boot order or boot priority
section.

Page 1 of 48
● Set the USB device as the first boot option to ensure the system
boots from the USB during startup.
● Save the changes and exit the BIOS settings.
2. Initial Setup:

● Restart your computer with the bootable USB inserted.


● Follow the on-screen prompts to boot from the USB device.
● Choose your preferred language, timezone, currency, and
keyboard settings during the initial setup.
3. Installation Process:

● Click on "Install Now" to begin the Windows installation process.

Page 2 of 48
● Enter the product key if prompted. This key is typically included
with your Windows purchase or provided during the download
process.
● Select the edition of Windows you have purchased (e.g.,
Windows 10 Home, Windows 10 Pro) and proceed with the
installation.
4. Partitioning and Drive Selection:

● Choose between an upgrade or custom installation.


● Upgrade: Preserves existing files and settings.
● Custom: Allows for a clean installation with the option to
create, delete, or format partitions.
● If performing a custom installation, select the drive where you
want to install Windows (usually the primary C: drive).

Page 3 of 48
5. Partition Management:

● If creating new partitions, follow the on-screen instructions to


allocate space and format partitions as needed.
● Exercise caution when deleting partitions, as this action will erase
all data on the selected drive.
6. Installation Progress:

● Once you've selected the installation drive, proceed with the


installation. The process may take some time, and your computer
may restart multiple times during the installation.

Page 4 of 48
7. Finalization and Setup:

● After the installation is complete, follow the on-screen instructions


to finalize setup options such as user accounts, privacy settings,
and network configuration.
● Sign in to your Microsoft account to access additional features
and services, or create a local user account if preferred.
8. Post-Installation Tasks:
● Install drivers for hardware components such as graphics cards,
network adapters, and peripherals.
● Update Windows to ensure you have the latest security patches
and system improvements.
● Install essential software and applications to personalize your
Windows experience.

By following these steps carefully and ensuring proper backups, you can
successfully install Windows using a bootable USB device. This method
provides a reliable way to set up or upgrade your operating system while
maintaining data integrity and system stability. Enjoy your newly installed
Windows OS and explore its features with confidence!

Page 5 of 48
Ques 2. Installation of Linux OS.

Linux offers a variety of distributions catering to different user needs. Whether


you're a beginner or an advanced user, there's a Linux distribution (distro)
suitable for you. Let's explore some popular Linux distros and delve into the
installation steps for Ubuntu Linux 12.04 LTS alongside Windows.

Popular Linux Distributions:

1. Ubuntu:
● Ubuntu stands as one of the most widely used Linux distributions,
known for its user-friendly interface and robust features. It's
suitable for both novices and experienced Linux users. Download
Ubuntu from Ubuntu's official website.
2. Linux Mint:
● Designed with beginners in mind, Linux Mint offers a familiar
Windows-like graphical user interface (GUI) and comes preloaded
with multimedia applications for a seamless experience. Get
Linux Mint from their official website.
3. Red Hat Enterprise Linux (RHEL):
● Geared towards business use, RHEL is a commercial Linux
version offering customer support and tailored solutions.
Purchase RHEL from Red Hat's website.
4. Fedora:
● Based on RHEL, Fedora provides cutting-edge open-source
software and a platform for experimentation. Download Fedora
from the Fedora Project.
5. Kali Linux:
● Kali Linux targets security professionals, offering tools for network
penetration testing, security research, and computer forensics. It's
a popular choice among ethical hackers. Download Kali Linux
from their official website.
6. Arch Linux:
● Arch Linux is a lightweight distribution favored by advanced
users. It requires knowledge of Bash Terminal commands and
customization to create a personalized Linux environment.
Download Arch Linux from their official website.

Page 6 of 48
Installing Ubuntu Linux 12.04 LTS Alongside Windows:

1. Backup Your Data:


● Before proceeding with the installation, it's crucial to back up all
your important data to prevent any loss during the process.
2. Obtain System Installation Media:
● Download the latest desktop version of Ubuntu 12.04 LTS from
Ubuntu's download page.
3. Booting the Installation System:
● There are several methods to boot the installation system, such
as using a CD-ROM, USB memory stick, or TFTP. Here, we'll
focus on booting from a CD-ROM.
● Change the boot order in your computer's BIOS settings to
prioritize the CD-ROM as the first boot device.
4. Installation Process:
● Insert the Ubuntu installation disk into the CD/DVD drive and
restart your computer.
● Follow the on-screen prompts to boot from the CD-ROM and
initiate the Ubuntu installation wizard.
● Choose your preferred language and select "Install Ubuntu" to
proceed.
5. Partitioning and Installation:
● Opt for manual partitioning ("Something else" option) to retain
your Windows installation and avoid data loss.
● Select the partition for Ubuntu installation (e.g., sdb) and
configure the mount point, file system type, and size.
● Continue with the installation process, including setting up your
user account, keyboard layout, and optional features like home
folder encryption.
6. Completion and Reboot:
● Once the installation completes, remove the CD-ROM and restart
your computer.
● During boot, you'll see a boot menu listing Windows and Ubuntu.
Choose Ubuntu to boot into your newly installed Linux system.
● Log in with your username and password to access Ubuntu 12.04
LTS.

Page 7 of 48
Exploring Ubuntu 12.04 LTS:

Upon logging in to Ubuntu, you'll encounter a user-friendly interface equipped


with essential applications and customization options. Take time to familiarize
yourself with Ubuntu's features, including software repositories, system
settings, and productivity tools.

Advanced Linux Configuration:

For advanced users, exploring Linux beyond basic installations opens doors to
customization, scripting, server management, and software development.
Delve into command-line tools, shell scripting, package management, and
system administration to harness Linux's full potential.

Conclusion:

Linux offers a diverse ecosystem of distributions catering to various user


needs. Installing Ubuntu Linux 12.04 LTS alongside Windows provides a
seamless dual-boot environment, allowing users to experience the best of
both worlds. Whether you're a beginner or an expert, Linux empowers you to
customize, innovate, and explore the world of open-source computing.

Page 8 of 48
Ques 3. Dual boot installation of Operating systems.

Part 1:

Creating a Bootable Drive

Firstly, it's essential to have Windows installed on your system before

proceeding with the installation of any other operating systems. Most other

operating systems, such as Linux distributions, are designed to seamlessly

coexist alongside Windows. However, for Mac systems, the process is

inherently different due to their unique architecture and the presence of

macOS as the default operating system.

Page 9 of 48
1. Downloading Rufus and Obtaining ISO Images:

● Visit https://rufus.ie/ to download Rufus, a tool specifically


designed for creating bootable USB drives. Rufus simplifies the
process of preparing a USB install drive, which is crucial for
installing an operating system on your computer.
● Alternatively, you can opt for an official install CD or DVD
provided by the respective operating system's official website.

Page 10 of 48
2. Installing Rufus and Acquiring OS Disk Images:

● Once Rufus is downloaded, follow the installation instructions


provided on the download page. The installation process is
straightforward and user-friendly, making Rufus accessible even
to less tech-savvy users.
● Obtain the ISO disk image for your desired operating system from
its official website. An ISO image contains all the necessary data
and files required for the installation process.
3. Preparing the USB Drive:
● Insert a blank USB flash drive into an available USB port on your
computer. Ensure that the USB drive has sufficient storage
capacity to accommodate the operating system you intend to
install.
● It's crucial to note that the USB drive should not contain any
essential data that you do not wish to lose, as the creation
process will overwrite its contents.

Page 11 of 48
4. Using Rufus to Create the Bootable Drive:
● Open Rufus, which features an intuitive interface resembling a
USB flash drive icon.
● Select your USB flash drive from the drop-down menu labeled
"Devices" within the Rufus application.
● Click on the "Select" button to navigate to and choose the ISO file
of the operating system you wish to install.
● Once the ISO file is selected, click on the "Start" button to initiate
the process of writing the ISO file to the USB drive. This process
may take some time, depending on the size of the ISO file and
the speed of your USB drive.

Creating a New Partition

Before proceeding with the installation of a new operating system and creating

a new partition, it's crucial to safeguard any important data on your system.

While partitioning a disk drive and installing a new OS typically does not result

in data loss, it's always advisable to create backups as a precautionary

measure.

Page 12 of 48
1. Accessing Disk Management:
● Right-click on the Windows Start menu, usually located in the
lower-left corner of the taskbar, to reveal a context menu.
● From the context menu, select "Disk Management" to launch the
Disk Management utility within Windows.
2. Shrinking the Volume:

● Within the Disk Management window, identify and right-click on


the drive where Windows is installed. This drive is often labeled
as the "C:" drive and represents the primary partition.
● Select the "Shrink Volume" option from the right-click menu to
initiate the process of shrinking the existing volume and creating
unallocated space on the hard drive.

3. Allocating Space for the New OS:


● Enter the desired amount of space (in megabytes, MB) that you
wish to allocate for the new operating system during the
partitioning process. It's crucial to allocate sufficient space while
ensuring that the remaining space continues to meet the
requirements of your existing OS.
● The amount of space you allocate will depend on factors such as
the size of the OS you plan to install and any additional software
or files you anticipate storing on the new partition.

Page 13 of 48
4. Completing the Shrinkage Process:
● Confirm the allocation of space by clicking on the "Shrink" button,
which will prompt the system to create a new partition of
unallocated space on your hard drive.
● The new partition of unallocated space is now ready to be utilized
for installing the new operating system while preserving your
existing data and system configuration.

Preparing Your PC for Dual Boot

To ensure a smooth dual-boot experience and avoid potential conflicts

between operating systems, it's essential to make specific adjustments and

configurations within your computer's settings, particularly within the BIOS or

UEFI firmware.

Preparing Your PC for Dual Boot

To ensure a smooth dual-boot experience and avoid potential conflicts


between operating systems, it's essential to make specific adjustments and
configurations within your computer's settings, particularly within the BIOS or
UEFI firmware.

Page 14 of 48
1. Disabling Fast Boot and Secure Boot:
● Fast Boot is a feature designed to expedite the system booting
process by minimizing startup time. However, it can sometimes
lead to compatibility issues, especially in dual-boot scenarios.
Disabling Fast Boot ensures smoother transitions between
operating systems.
● Secure Boot, on the other hand, is a security feature that
prevents the loading of unauthorized operating systems and
drivers during the boot process. While beneficial for security, it
can interfere with the installation of alternative operating systems.
Disabling Secure Boot is often necessary for successful dual-boot
setups.
2. Accessing BIOS/UEFI Settings:
● The process of accessing the BIOS or UEFI settings varies
depending on the manufacturer and model of your computer.
Commonly used keys during system startup to access these
settings include F1, F2, F9, F12, Esc, or Delete. Refer to your
computer's documentation or manufacturer's website for specific
instructions.
3. Changing Boot Order and Settings:
● Within the BIOS or UEFI settings, locate the Boot menu or Boot
Order section, which determines the sequence in which devices
are checked for bootable operating systems during startup.
● Adjust the boot order settings to prioritize booting from a USB
drive or the installation media (CD/DVD) if applicable. This
ensures that the system recognizes and boots from the device
containing the new operating system you intend to install.
4. Saving BIOS/UEFI Changes:
● After making the necessary adjustments to Fast Boot, Secure
Boot, and boot order settings, save the changes within the BIOS
or UEFI interface.
● Select the option to save and exit the BIOS/UEFI settings, which
will prompt the system to restart and apply the modified
configurations.

Page 15 of 48
Installing the New Operating System

Once you have created a bootable drive, prepared the partition, and adjusted
your computer's settings, you're ready to proceed with the installation of the
new operating system alongside your existing OS.

1. Inserting the Installation Media:


● If you used Rufus to create a bootable USB drive, insert the USB
flash drive into an available USB port on your computer.
● Alternatively, if you are using an installation CD/DVD, insert it into
the appropriate drive (CD/DVD-ROM).
2. Restarting Your Computer:

● Restart your computer to initiate the installation process from the


bootable USB drive or installation CD/DVD.
● Ensure that the system recognizes the inserted installation media
and boots from it according to the adjusted boot order settings.

Page 16 of 48
3. Navigating the Installation Setup:

● Upon successful booting from the installation media, the setup


program for the new operating system will load.
● Follow the on-screen instructions to select your preferred
language, keyboard layout, and any other regional settings as
required by the installation wizard.
4. Entering Product Keys or Serial Numbers:
● Some operating systems, particularly proprietary ones like
Windows, may require you to enter a valid product key or serial
number during the installation process.
● If prompted, enter the necessary alphanumeric code provided
with your OS purchase to validate and activate the installation.
5. Selecting Installation Options:
● When prompted to select the type of installation, opt for the
"Custom," "Other," "Advanced," or similar option rather than a
standard installation.
● Choosing the custom installation option allows you to specify the
target drive or partition where the new OS will be installed,
ensuring that it does not overwrite your existing OS or data
unintentionally.

Page 17 of 48
6. Formatting and Partitioning:

● Select the newly created partition or unallocated space on your


hard drive as the destination for the new operating system
installation.
● Depending on the OS being installed, you may need to format the
partition with a specific file system (e.g., Ext4 for Linux
distributions) and configure any additional settings such as a
swap area or system partition.
7. Completing the Installation Process:
● Follow the step-by-step instructions provided by the installation
wizard to configure user preferences, such as creating a
username, setting a password, and customizing time/date
settings.
● Ensure that all required settings and options are configured
correctly before proceeding with the installation process to avoid
any potential issues or errors.

Page 18 of 48
8. Rebooting and Switching Between Operating Systems:
● Upon successful completion of the installation, reboot your
computer to finalize the setup and apply the changes.
● During the boot process, you will now see a boot menu that
allows you to choose between the installed operating systems.
Use the arrow keys or mouse to select the desired OS and press
Enter to boot into it.
● You can switch between the installed operating systems by
rebooting your computer and selecting the appropriate OS from
the boot menu each time.

By following these comprehensive steps, you can effectively create a bootable


drive, prepare a new partition, configure your PC for dual booting, and
successfully install multiple operating systems to enjoy the benefits of a
dual-boot setup without compromising data integrity or system stability.

Page 19 of 48
Ques 4. Implementation of FCFS Scheduling algorithm
● First Come First Serve CPU Scheduling Algorithm shortly known as
FCFS is the first algorithm of CPU Process Scheduling Algorithm.
Basically, we aren’t assigning any priority to the process. Whosoever
comes first to the RAM will get the CPU first.
● It is a non-preemptive scheduling algorithm, that is, we shall not be
preempting any process in between. Whenever a process is scheduled
to the CPU, until completion that process will not be preemptied.

Characteristics of FCFS CPU Process Scheduling


1. Implementation is simple.
2. Does not cause any causalities while using
3. It adopts a non preemptive and preemptive strategy.

Advantages of FCFS CPU Process Scheduling


1. In order to allocate processes, it uses the First In First Out queue.
2. The FCFS CPU Scheduling Process is straight forward and easy to
implement.

Disadvantages of FCFS CPU Process Scheduling


● FCFS CPU Scheduling Algorithm has Long Waiting Time
● FCFS CPU Scheduling favors CPU over Input or Output operations

Important Abbreviations
1. CPU - - - > Central Processing Unit
2. FCFS - - - > First Come First Serve
3. AT - - - > Arrival Time
4. BT - - - > Burst Time
5. WT - - - > Waiting Time
6. TAT - - - > Turn Around Time
7. CT - - - > Completion Time

Page 20 of 48
C++ Program to Demonstrate the use of The FCFS Scheduling
Algorithm in Operating System

// C++ program for implementation of FCFS


// scheduling
#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes

Page 21 of 48
findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details


cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


int burst_time[] = {10, 5, 8};

findavgTime(processes, n, burst_time);
return 0;
}

Page 22 of 48
Page 23 of 48
Page 24 of 48
Ques 5. Implementation of SJF Scheduling algorithm
● The shortest job first (SJF) or shortest job next, is a scheduling policy
that selects the waiting process with the smallest execution time to
execute next.
● Among arrived processes, process with least burst time (execution time)
will be given preference
● It is a non-preemptive scheduling algorithm

Characteristics of SJF Scheduling:


● Shortest Job first has the advantage of having a minimum average
waiting time among all scheduling algorithms.
● It is a Greedy Algorithm.
● It may cause starvation if shorter processes keep coming. This problem
can be solved using the concept of ageing.

Advantages of SJF:
● SJF is better than the First come first serve(FCFS) algorithm as it
reduces the average waiting time.
● SJF is generally used for long term scheduling

Disadvantages of SJF:
● SJF may cause very long turn-around times or starvation.
● In SJF job completion time must be known earlier, but sometimes it is
hard to predict.

Page 25 of 48
C++ Program to Demonstrate the use of The SJF Scheduling Algorithm
in Operating System:

Page 26 of 48
Ques 6. Implementation of Round-Robin Scheduling algorithm
Round Robin is a CPU scheduling algorithm where each process is cyclically
assigned a fixed time slot. It is the preemptive version of the First come First
Serve CPU Scheduling algorithm.
● Round Robin CPU Algorithm generally focuses on Time Sharing
technique.
● The period of time for which a process or job is allowed to run in a
pre-emptive method is called time quantum.

Characteristics of Round Robin CPU Scheduling Algorithm


● It is simple, easy to implement, and starvation-free as all processes get
a fair share of CPU.
● One of the most commonly used techniques in CPU scheduling is a
core.
● It is preemptive as processes are assigned CPU only for a fixed slice of
time at most.
● The disadvantage of it is more overhead of context switching.

Advantages of Round Robin CPU Scheduling Algorithm


● There is fairness since every process gets an equal share of the CPU.
● The newly created process is added to the end of the ready queue.
● A round-robin scheduler generally employs time-sharing, giving each
job a time slot or quantum.
● While performing a round-robin scheduling, a particular time quantum is
allotted to different jobs.

Disadvantages of Round Robin CPU Scheduling Algorithm


● There is Larger waiting time and Response time.
● There is Low throughput.
● There is Context Switches.
● Gantt chart seems to come too big (if quantum time is less for
scheduling. For Example:1 ms for big scheduling.)

Page 27 of 48
C++ Program to Demonstrate the use of The ROUNDROBIN Scheduling
Algorithm in Operating System:

Page 28 of 48
Page 29 of 48
Ques 7. Vi Editor & its commands
vi Editor
The default editor that comes with the Linux/UNIX operating system is called
vi (visual editor). Using vi editor, we can edit an existing file or create a new
file from scratch. we can also use this editor to just read a text file.

vi edit modes
The Vi editor has two modes: Command and Insert. When you first open a file
with Vi, you are in Command mode. Command mode means you can use
keyboard keys to navigate, delete, copy, paste, and do a number of other
tasks—except entering text.

To enter Insert mode, press i. In Insert mode, you can enter text, use the Enter
key to go to a new line, use the arrow keys to navigate text, and use vi as a
free-form text editor. To return to Command mode, press the Esc key once.

In Vi's Command mode, almost every letter on the keyboard has a function.

To save a file, you must first be in Command mode. Press Esc to enter
Command mode, and then type :wq to write and quit the file. The other,
quicker option is to use the keyboard shortcut ZZ to write and quit. In Vi, write
means save, and quit means exit. If you’ve made mistakes along the way
while editing and want to back out (abandon) all non-saved changes, enter
Command mode by pressing Esc and typing :q! This command quits without
saving any changes and exits Vi.

Vi shortcuts

The best way to learn Vi is to create a new file and try it out for yourself. Feel
free to use the common keyboard shortcut list below to help you learn Vi’s
extensive vocabulary. This list of shortcuts is by no means exhaustive, but
they will enable you to edit files and learn Vi in a short amount of time.

● $ vi <filename> — Open or edit a file.


● i — Switch to Insert mode
● :w — Save and continue editing.
● :wq or ZZ — Save and quit/exit vi.
● :q! — Quit vi and do not save changes.
● yy — Yank (copy) a line of text. p — Paste a line of yanked text below
the current line.

Page 30 of 48
● o — Open a new line below the current line
● :num — Display the current line’s line number
● dd — Delete an entire line
● / — Vi will move the cursor to the next occurrence of the pattern
● ? — Vi will move the cursor to the previous occurrence of the pattern

Page 31 of 48
Ques 8. Shell Commands
Shell

A shell is a special user program that provides an interface to the user to use
operating system services. Shell accepts human-readable commands from
the user and converts them into something which the kernel can understand. It
is a command language interpreter that executes commands read from input
devices such as keyboards or from files. The shell gets started when the user
logs in or starts the terminal.

Basic Shell Commands

1. Displaying the file contents on the terminal:


○ cat: It is generally used to concatenate the files. It gives the
output on the standard output.
○ more: It is a filter for paging through text one screenful at a time.

○ less: It is used to viewing the files instead of opening the


file.Similar to more command but it allows backward as well as

Page 32 of 48
forward movement.

○ head : Used to print the first N lines of a file. It accepts N as input


and the default value of N is 10.
○ tail : Used to print the last N-1 lines of a file. It accepts N as input
and the default value of N is 10.

Page 33 of 48
2. File and Directory Manipulation Commands:
○ mkdir : Used to create a directory if not already exist. It accepts
the directory name as an input parameter.

○ cp : This command will copy the files and directories from the
source path to the destination path. It can copy a file/directory
with the new name to the destination path. It accepts the source
file/directory and destination file/directory.

Page 34 of 48
○ mv : Used to move the files or directories. This command’s
working is almost similar to cp command but it deletes a copy of
the file or directory from the source path.

○ rm : Used to remove files or directories.

○ touch : Used to create or update a file.

Page 35 of 48
3. Extract, sort, and filter data Commands:
○ grep : This command is used to search for the specified text in a
file.

○ grep with Regular Expressions: Used to search for text using


specific regular expressions in file.

○ sort : This command is used to sort the contents of files.

○ wc : Used to count the number of characters, words in a file.

Page 36 of 48
○ cut : Used to cut a specified part of a file.

4. Basic Terminal Navigation Commands:


○ ls : To get the list of all the files or folders.
○ ls -l: Optional flags are added to ls to modify default behavior,
listing contents in extended form -l is used for “long” output
○ ls -a: Lists of all files including the hidden files, add -a flag
○ cd: Used to change the directory.
○ du: Show disk usage.
○ pwd: Show the present working directory.
○ man: Used to show the manual of any command present in Linux.
○ rmdir: It is used to delete a directory if it is empty.
○ ln file1 file2: Creates a physical link.
○ ln -s file1 file2: Creates a symbolic link.
○ locate: It is used to locate a file in Linux System
○ echo: This command helps us move some data, usually text into
a file.
○ df: It is used to see the available disk space in each of the
partitions in your system.
○ tar: Used to work with tarballs (or files compressed in a tarball
archive)

Page 37 of 48
Ques 9. Shell Scripting- Using variables
Shell Scripting
Shell scripting is the process of writing a series of commands for execution
within a Unix-like operating system's command-line interpreter, known as the
shell. The shell acts as an interface between the user and the operating
system, interpreting commands entered by the user or read from a script file
and executing them.

In shell scripting, commands are typically written in a simple text file, often
with the ".sh" extension, and then executed as a script. These scripts can
automate repetitive tasks, perform system administration tasks, or orchestrate
complex sequences of commands.

How Do You Identify a Bash Script?

File extension of .sh.


By naming conventions, bash scripts end with a .sh. However, bash scripts
can
run perfectly fine without the sh extension.

Scripts start with a bash bang

Scripts are also identified with a shebang. Shebang is a combination of bash #


and bang ! followed the the bash shell path. This is the first line of the script.
Shebang tells the shell to execute it via bash shell. Shebang is simply an
absolute path to the bash interpreter.

Below is an example of the shebang statement. #! /bin/bash


The path of the bash program can vary. We will see later how to identify it

Provide execution rights to your user

Modify the file permissions and allow execution of the script by using the
command : chmod u+x File_name.sh

chmod modifies the existing rights of a file for a particular user. We are adding
+x to user u.

Page 38 of 48
Run the script

You can run the script in the following ways:


● ./hello_world.sh
● bash hello_world.sh.

Shell Scripting- Using variables

Variables let you store data. You can use variables to read, access, and
manipulate data throughout your script.

In Bash, you can use and set the variable values in the following ways:
1. Assign the value directly: country=India
2. Assign the value based on the output obtained from a program or
command, using command substitution. Note that $ is required to
access an existing variable's value.
same_country=$country
This assigns the value of country to the new variable same country

Page 39 of 48
Ques 10. Shell Scripting- Input & Output
In shell scripting, input and output operations are fundamental for interacting
with users and processing data. Here's a detailed explanation of how to
handle input and output in a shell script:

1. Echo Command:

The `echo` command is used to print output to the terminal. It's also
commonly used to prompt users for input.

Syntax:
echo "What is your name?"

2. Read Command:
The `read` command is used to read input from the user and store it in a
variable.

Syntax:
read name

In the above line, the user's input will be stored in the variable `name`.

3. Printing Output:

You can print output with variables using `echo`.

Syntax:

echo "Hello $name, you are $age years old."

In this line, the values of variables `name` and `age` will be inserted into the
output string.

4. Running the Script:

To run the script, save it in a file (e.g., `ishan_Q10.sh`). Make it executable


using `chmod u+x ishan_Q10.sh`. Then, execute it with `bash.ishan_Q10.sh`.

Page 40 of 48
Ques 11. Shell Scripting- Data types
In shell scripting, variables don't have explicit data types like in some other
programming languages. Instead, they are treated as strings by default.
However, you can manipulate and interpret them in different ways depending
on the context. For example, you can perform arithmetic operations on
variables, and the shell will interpret them as numbers if they contain only
numeric values. Additionally, you can explicitly specify the data type or enforce
type checking through various methods, such as using commands like
`declare` or `typeset` with options like `-i` for integer variables.

1. Strings: Shell scripts handle text as strings. You can manipulate strings
using various operators and commands like echo, grep, sed, awk, etc.
2. Numbers: Shell scripts treat numbers as strings by default, but you can
perform arithmetic operations using special constructs like $((...)), expr,
and bc (a command-line calculator).
○ Using $((...)): This construct allows for arithmetic operations
directly within double parentheses. For example, result=$((5 + 3))
sets result to 8.
○ expr: This is an external command used for basic arithmetic. For
instance, result=$(expr 5 + 3) assigns 8 to result.
○ bc: For more advanced arithmetic, including floating-point
calculations, you can use bc. Example: result=$(echo "5.5 + 3.2" |
bc) sets result to 8.7.
3. Arrays: Shell scripting supports arrays, which can hold multiple values.
Arrays are indexed starting from 0, and you can access array elements
using their indices or iterate over them using loops.

Here’s a simple example illustrating these data types:

#!/bin/bash

# String manipulation
name="Alice"
echo "Hello, $name!"

# Arithmetic operations
num1=10
num2=5
result=$((num1 + num2))
echo "The result of $num1 + $num2 is $result"

# Arrays

Page 41 of 48
fruits=("Apple" "Banana" "Orange")
echo "The first fruit is ${fruits[0]}"
echo "All fruits: ${fruits[@]}"

When run, this script will output:

Hello, Alice!
The result of 10 + 5 is 15
The first fruit is Apple
All fruits: Apple Banana Orange

Page 42 of 48
Ques 12. Shell Scripting- Use of arithmetic operators

Below are the operators supported by bash for mathematical calculations:

Numerical expressions can also be calculated and stored in a variable using


the syntax below:

var=$((expression))

Fractions are not correctly calculated using the above methods and truncated.

For decimal calculations, we can use bc command to get the output to a particular
number of decimal places. bc (Bash Calculator) is a command line calculator that
supports calculation up to a certain number of decimal points.

echo "scale=2;22/7" | bc

Where scale defines the number of decimal places required in the output.

Page 43 of 48
Ques 13. Shell Scripting- if control statement programs

Conditional Statements (Decision Making)

Conditions are expressions that evaluate to a boolean expression (true or


false). To check conditions, we can use if, if-else, if-elif-else and nested
conditionals. The structure of conditional statements is as follows:

● if...then...fi statements
● if...then...else...fi statements
● if..elif..else..fi
● if..then..else..if..then..fi..fi.. (Nested Conditionals)
Syntax:
if [[ condition ]]
Then
statement
elif [[ condition ]]; then
statement
Else
do this by default
Fi

Page 44 of 48
Ques 14. Shell Scripting- while control statement

While loop

While loops check for a condition and loop until the condition remains true. We
need to provide a counter statement that increments the counter to control
loop
execution.

Running the script: Printing the numbers by providing starting and ending limit
using while loop

Page 45 of 48
Running the script: Infinity loop with user input using while loop

Page 46 of 48
Ques 15. Shell Scripting- for control statement
The for loop, just like the while loop, allows you to execute statements a
specific number of times. Each loop differs in its syntax and usage.

Running the script: Printing the numbers by providing starting and ending limit
using For loop

#!/bin/bash
#This is the basic example of 'for loop'.

learn="Start learning from Javatpoint."

for learn in $learn


do
echo $learn
done

echo "Thank You."

Page 47 of 48
Running the Script: Finding Factorial using for loop.

Page 48 of 48

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy