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

foss-full-notes

The document outlines the course content for a Free and Open Source Software (FOSS) class at the Muslim Association College of Arts and Science, affiliated with the University of Kerala. It covers various modules including concepts of open source software, Linux features and commands, shell programming, and the differences between free software and proprietary software. Additionally, it discusses the Free Software Movement, the Free Software Foundation, and the General Public License (GPL).

Uploaded by

Akhila p
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)
11 views

foss-full-notes

The document outlines the course content for a Free and Open Source Software (FOSS) class at the Muslim Association College of Arts and Science, affiliated with the University of Kerala. It covers various modules including concepts of open source software, Linux features and commands, shell programming, and the differences between free software and proprietary software. Additionally, it discusses the Free Software Movement, the Free Software Foundation, and the General Public License (GPL).

Uploaded by

Akhila p
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/ 69

lOMoARcPSD|19230806

FOSS FULL 2023 - FOSS FULL 2023

Open Elective (University of Kerala)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Akhila P ([email protected])
lOMoARcPSD|19230806

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

MUSLIM ASSOCIATION COLLEGE OF ARTS AND SCIENCE


Panavoor,Thiruvananthapuram,Kerala
(Affiliated to the University of Kerala)

Department of Computer Science


CS1543 : FREE AND OPEN SOURCE SOFTWARES (FOSS)

S5 BSc Computer Science

Name : ……………………………………………………………………………………………

Candidate Code: ……………………………………………………………………………..

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

CS1543 : FREE AND OPEN SOURCE SOFTWARES (FOSS)

COURSE CONTENT
Module I: Open source software: concepts, features, benefits over proprietary software,
examples, Free software: concepts, features, advantages, Free software Vs Open Source software,
Free and Open Source Software (FOSS), Four essential freedoms, Free software movements, free
software foundation(FSF), history, policies, GPL, free operating systems

Module II: Linux: features, history, various Linux distributions, Linux architecture, kernel and shell,
Linux desktop environments- GNOME and KDE, Linux File System and Directories, types of files,
Installing and Configuring Linux, File access permissions, understanding system administration

Module III: Linux Commands: date, time, who, echo, man, info, cal, pwd, more, less, head, tail,
mkdir,cd, cp, mv, rm, touch, sort, wc, cut, cat with options, ls with options ,grep with options,
chmod, diff, mounting the file system, command line processing etc. Types of editors in Linux,
Introduction to vi editor, modes in vi editor, common vi editor commands for open a file, save a
file, delete a file, quit a file etc

Module IV: Shell Programming: Introduction to Linux Shell and Shell Scripting, types of shells in
Linux, steps in creating a shell script, write and run shell scripts, shell variables and printing,
deleting shell variables, script permissions and names, scripting guidelines, adding shell
comments, shell variables, constants, operators, conditional statements, looping statements,
using arrays, shell functions,files, shell built-in functions

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Module I
Open Source Software
Concepts, features, benefits over proprietary software, examples, Free software: concepts,
features, advantages, Free software Vs Open Source software, Free and Open Source Software
(FOSS), Four essential freedoms, Free software movements, free software foundation(FSF),
history, policies, GPL, free operating systems

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Open Source Software - Concept


 A software whose source code is freely distributed with a license to study, change and
further distributed to anyone for any purpose is called open source software.
 Open source software is generally a team effort where dedicated programmers improve
upon the source code and share the changes within the community.
 Open source software provides these advantages to the users due to its thriving
communities −

 Security

 Affordability

 Transparent

 Interoperable on multiple platforms

 Flexible due to customizations

 Localization is possible

 Open source code is usually stored in a public repository and shared publicly.

 Anyone can access the repository to use the code independently or contribute
improvements to the design and functionality of the overall project.

 OSS usually comes with a distribution license. This license includes terms that define how
developers can use, study, modify, and most importantly, distribute the software

 Examples of OSS

 GNU/Linux
 Mozilla Firefox
 VLC media player
 SugarCRM
 GIMP
 VNC
 Apache web server
 LibreOffice
 jQuery

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Features of open-source software

1.Innovation

 OSS encourages the collaboration of ideas, resources, and data which has contributed to
many of the most essential tech developments of our generation.
 Indeed, open source code is increasingly incorporated into many other software products,
allowing developers to save time and effort by leveraging code developed by others.
 Moreover, it also helps the software and the code to evolve, improve, and remain relevant
while enabling more tech endeavours.

2.Freedom

 One of the key benefits of open source software is that it is a platform where programmers
are provided with freedom at no substantial cost.
 With open-source software, organizations and programmers can operate and use the
source code in whatever way they want.
 Moreover, they can study the software and change it according to their requirement for
more effective computing.

3.Integrity

 In the open source software, organizations have the liberty to analyze the code and make
changes to it by adding security-based codes to the software.
 Furthermore, the users of open source software have a large user community who
collectively identify and tackle any issues or security vulnerabilities in the software with
the help of beta testers for a safer experience.

4.Continuity

 A major reason why organizations prefer to utilize and optimize open-source software is
because of the business continuity it provides them.
 The open-source software is more efficient and performs better in business continuity
than proprietary software.

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

 By being readily available and accessible, companies do not have to delay operations to
construct and code software from scratch, which saves time and cost, while enhancing
employees’ effectiveness.

5.Giving Back to the Community

 Open-source software is beneficial to many people.


 Individual programmers can utilize the accessible software as a learning medium to
improve their coding skills.
 Moreover, businesses make use of it and modify it for the development of their own
services and technology, redistributing the modified versions to other developers to
continue the chain.
 Consumers and society as a whole benefit from the improved and refined technology and
commodities that are created due to the flexibility of open data and open-source
software.

Advantages of Free Software over Proprietary Software

1.No Royalty Fee for Free Software

The 'free' in Free Software refers to the freedom to use it as and how you want. Users are free to
use, study, modify and redistribute the softwar

2.Freedom with Code

Free Software gives users the freedom to use the software or program for any purpose of choice
without limitation. Programmers can study the source code and modify it to custom-build
software for specialized purposes.

3.Free Software is Secure

FOSS has a lot of committed code contributors who keep the software secure and issue-free. The
wide network of free software users alerts the community of any vulnerability and issues

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

4.Free Software is Not Restricted

You need a valid license to use proprietary software. Unless the license allows it you are not
permitted to use the software in any other systems or devices. But in contrast, the OSS. You can
copy and use it any number of times.

5.Free Software Means No Vendor Dependence

Free Software have the freedom to pick and choose the best of the available software and not be
bound by vendor lock-in standards. With Free Software, you own your data and choice of the
technology stack.

Free Software / Freeware

A software that is available free of cost for use and distribution but cannot be modified as its
source code is not available is called freeware. Examples of freeware are Google Chrome, Adobe
Acrobat PDF Reader, Skype, etc.

Features /Advantages of free software.

Often, free software has the same features as its high-priced proprietary counterparts – andthat is
only one of the many advantages:

1. Free to Download:- No cost to download free software


2. Many Choices:- There are more than 6,500 pieces of free software available today.
3. Large Communities:-Many free software programs have large and active communities
online that offer support to users of free software via blogs and forums.
4. Supportive of Social Movement:- The use of free software supports a movement that
believes computer users should be free from technology that conducts surveillance and
gathers information about what users do on their devices.
5. Shared Improvements:-Users are allowed to have source code, study it, make functional
changes to a program, and redistribute the modified software to others in any way they
choose.

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Open-Source Software Vs Free Software

S.No. Free Software Open Source Software

The term "open source" was first used in


The Free Software Foundation tern was first
1. response to the limitations of free software in
used in the 1980s.
the late 1990s.

Software plays a significant role in people's All software is the same. It has no definite
2.
daily lives. ethical implications.

Social freedom is correlated with software Ethics should be connected to people, not to
3.
freedom. software.

A value that is more significant than any The idea of freedom is not unqualified. Freedom
4.
financial benefit is freedom. ought to be granted, not forced.

Not every piece of open-source software is also


5. All open- source software is free.
cost-free.

Many different licences are used to distribute


open-source software, some of which are quite
6. Free software doesn't have this issue.
onerous and force the development of paid
versions of the programme.

Examples: A sizable database of free Examples of open-source products


7. software packages is kept by the Free include the full office suite,
Software Directory. Some of the most well- LibreOffice, the Apache HTTP Server,

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

known examples include the Linux kernel, Open-Source Commerce, Mozilla


the BSD and Linux operating systems, the Firefox, and Chromium (the project
GNU Compiler Collection and C library, the where the majority of development
MySQL relational database, the Apache web for the freeware Google Chrome is
server, and the Send mail transport agent. done).

Proprietary Software
Software that can be used only by obtaining license from its developer after paying for it is called
proprietary software.
An individual or a company can own such proprietary software. Its source code is often closely
guarded secret and it can have major restrictions like –
• No further distribution
• Number of users that can use it
• Type of computer it can be installed on, example multitasking or single user, etc.
For example, Microsoft Windows is a proprietary operating software that comes in many editions
for different types of clients like single-user, multi-user, professional, etc.

What is FOSS?
FOSS means Free and Open Source Software. It doesn’t mean the software is free of cost. It means
that the software's source code is open for all and anyone is free to use, study and modify the
code. This principle allows others to contribute to developing and improving a software like a
community.
 Any user should be able to run the software for any purpose.
 Users should be free to see the source code of the software and if need be, users should
be allowed to modify the code as well.
 Users should be free to distribute copies of the software to others.
 If a user modifies the code, she/he should be free to distribute the modified code to
others. The modified code must have the source code open.

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Free Software Movement


 In the 60s and 70s, computers were hardware focused and the hardware was expensive.
They were mainly used by academics in universities or researchers in labs. The limited
amount of software used to come for free or with their source code and the users were
allowed to modify the source code to suit their needs.
 In the late 70s and early 80s, the manufacturer’s stopped distributing source code in an
attempt to not let their software run on their competitor’s computers.
 This restrictive licensing led to the inconvenience and dislike of people who were used to
and fond of modifying software. In the mid-80s, Richard Stallman started the Free
Software Movement.
 Stallman specified four essential fundamental freedom for software to be Free and Open
Source Software.

Four Essential Freedom


The free software movement is a world wide effort that campaigns for the creation, use, and
adoption of free software that entitles users to four essential freedoms:
• Freedom 0-The freedom to run the program as they wish, for any purpose
• Freedom 1-The freedom to study how the program works, and change it so it does their
computing as they wish Access to the source code is a precondition for this.
• Freedom 2-The freedom to redistribute copies so they can help others
• Freedom 3-The freedom to distribute copies of their modified versions to By doing this
they can give the whole community a chance to benefit from their changes. Access to
the source code is a precondition for this.

Free Software Foundation (FSF)


The Free Software Foundation (FSF) is a non-profit corporation founded by Richard Stallman on
October 4th, 1985 to support the free software movement, a copyleft-based movement which
aims to promote the universal freedom to distribute and modify computer software without
restriction. The FSF is incorporated in Boston, Massachusetts, USA.
 The Free Software Foundation was established to encourage the development of free
software.

10

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

 The free software movement, which liberated users to freely create and share their
software and programs, was a major driver behind this foundation.
 FSF’s primary objective is to instigate the rejection of propriety software that cannot be
shared, published or altered legally.
 FSF also maintains a team of in-house software programmers that develop software and
applications that can be revised and distributed by end users, and are available under the
GNU General Public License (GPL).

General Public License (GPL)

 GPL or General Public License, sometimes also called GNU GPL, is the most commonly
used free software license.
 It was written by Richard Stallman of Free Software Foundation for GNU Project.
 This license allows software to be freely used, modified, and redistributed by anyone.
 WordPress is also released under the GPL license, which means that WordPress is an open
source software that can be used, modified, and extended by anyone.
 It provides the core basic values that the project believes in.

1. Anyone can download and run the software


2. Anyone can modify it
3. Anyone can redistribute free copies of the software
4. Anyone can distribute modified versions of the software.

Free Operating System (Free OS)


If an OS if a Free OS then it satisfy the following criteria:

 They cost the end-user absolutely nothing to download the installation media and install.
 They are at least predominantly made of open-source software (OSS). Any non-OSS included in
this system is at least freeware and not trialware or freemium.
 Example: Linux

*******END OF MODULE 1*******

11

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Module II: Linux


features, history, various Linux distributions, Linux architecture, kernel and shell, Linux desktop
environments- GNOME and KDE, Linux File System and Directories, types of files, Installing and
Configuring Linux, File access permissions, understanding system administration

12

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux
 Linux is a community of open-source Unix like operating systems that are based on
the Linux Kernel.
 It was initially released by Linus Torvalds on September 17, 1991. It is a free and open-
source operating system and the source code can be modified and distributed to anyone
commercially or noncommercially under the GNU General Public License.
 Initially, Linux was created for personal computers and gradually it was used in other
machines like servers, mainframe computers, supercomputers, etc.
 The biggest success of Linux is Android(operating system) it is based on the Linux kernel
that is running on smart phones and tablets.
 Linux is one of popular version of UNIX operating System.
 It is open source as its source code is freely available.
 It is free to use.
 Linux was designed considering UNIX compatibility.
 Its functionality list is quite similar to that of UNIX.

Linux Features
o Multiuser capability: Multiple users can access the same system resources like memory,
hard disk, etc. But they have to use different terminals to operate.

o Multitasking: More than one function can be performed simultaneously by dividing the
CPU time intelligently.

o Portability: Portability doesn't mean it is smaller in file size or can be carried in pen drives
or memory cards. It means that it support different types of hardware.

o Security: It provides security in three ways namely authenticating (by assigning password
and login ID), authorization (by assigning permission to read, write and execute) and
encryption (converts file into an unreadable format).

o Graphical User Interface (X Window system): Linux is command line based OS but it can be
converted to GUI based by installing packages.

o Support's customized keyboard: As it is used worldwide, hence supports different


languages keyboards.

13

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

o Application support: It has its own software repository from where users can download
and install many applications.

o File System: Provides hierarchical file system in which files and directories are arranged.

o Open Source: Linux code is freely available to all and is a community based development
project.

Linux Distributions

There are on an average six hundred Linux distributors providing different features. Here, we'll
discuss about some of the popular Linux distros today.

1) Ubuntu

 It came into existence in 2004 by Canonical and quickly became popular.


 Canonical wants Ubuntu to be used as easy graphical Linux desktop without the use of
command line.
 It is the most well known Linux distribution.
 It comes with a lots of pre-installed apps and easy to use repositories libraries.
 Earlier, Ubuntu uses GNOME2 desktop environment but now it has developed its own
unity desktop environment.
 It releases every six months and currently working to expand to run on tablets and smart
phones.

2) Linux Mint

 Mint is based on Ubuntu and uses its repository software so some packages are common
in both.
 Earlier it was an alternative of Ubuntu because media codecs and proprietary software are
included in mint but was absent in Ubuntu.
 But now it has its own popularity and it uses cinnamon and mate desktop instead of
Ubuntu's unity desktop environment.

14

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

3) Debian

 Debian has its existence since 1993 and releases its versions much slowly then Ubuntu and
mint.
 This makes it one of the most stable Linux distributor.
 Ubuntu is based on Debian and was founded to improve the core bits of Debian more
quickly and make it more user friendly.
 Every release name of Debian is based on the name of the movie Toy Story.

4) Red Hat Enterprise / CentOS

 Red hat is a commercial Linux distributor.


 There products are red hat enterprise Linux (RHEL) and Fedora which are freely available.
 Red hat uses trademark law to prevent their software from being redistributed.
 CentOS is a community project that uses red hat enterprise Linux code but removes all its
trademark and make it freely available.
 In other words, it is a free version of RHEL and provide a stable platform for a long time.

5) Fedora

 It is a project that mainly focuses on free software and provides latest version of software.
 It doesn't make its own desktop environment but used 'upstream' software. By default it
has GNOME3 desktop environment.
 It is less stable but provides the latest stuff.

15

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Architecture of Linux

Linux architecture has the following components:

1.The Kernel
2.System Library
3.Hardware layer
4.System
5.Shell utility.

1. Kernel:-

 The kernel is one of the core section of an operating system.


 It is responsible for each of the major actions of the Linux OS.
 This operating system contains distinct types of modules and cooperates with underlying
hardware directly.
 The kernel facilitates required abstraction for hiding details of low-level hardware or
application programs to the system.

There are some of the important kernel types which are mentioned below:

16

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

o Monolithic Kernel

o Micro kernels

o Exo kernels

o Hybrid kernels

2. System Libraries:-

 These libraries can be specified as some special functions.


 These are applied for implementing the operating system's functionality and don't need
code access rights of the modules of kernel.

3. System Utility Programs:-

 It is responsible for doing specialized level and individual activities.

4. Hardware layer:-

 Linux operating system contains a hardware layer that consists of several peripheral
devices like CPU, HDD, and RAM.

5. Shell:-

 It is an interface among the kernel and user.


 It can afford the services of kernel.
 It can take commands through the user and runs the functions of the kernel.
 The shell is available in distinct types of OSes.
 These operating systems are categorized into two different types, which are the graphical
shells and command-line shells.
 The graphical line shells facilitate the graphical user interface, while the command line
shells facilitate the command line interface.

17

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux Kernel and Shell


Kernel − The kernel is the heart of the operating system. It interacts with the hardware and most
of the tasks like memory management, task scheduling and file management.

Shell − The shell is the utility that processes your requests. When you type in a command at your
terminal, the shell interprets the command and calls the program that you want. The shell uses
standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are the most famous shells
which are available with most of the Unix variants.

Linux Desktops Environment


 One exciting aspect of Linux unlike with Windows and Mac OS X, is its support for
numerous number of desktop environments, this has enabled desktop users to choose the
appropriate and most suitable desktop environment to best work with, according to their
computing needs.
 A Desktop Environment is an implementation of the desktop consist of collection of
different user and system programs running on top of an operating system, and share a
common GUI (Graphical User Interface), also known as a graphical shell.
1.GNOME
 GNOME is probably the most popular desktop environment among Linux users, it is free
and open source, simple, yet powerful and easy to use.
 It is designed from ground up to offer Linux desktop users a wonderful and exciting
computing experience.
 It presents a activities overview for easy access to basic tasks, provides a powerful search
tool for users to access their work from any place.
Features:
• Comes with Nautilus as default file manager
• Supports desktop notifications using a convenient messaging system
• Enables on/off switching of desktop notifications and many more

18

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

KDE
 KDE stands for K Desktop Environment. It is a desktop environment for Linux based
operation system.
 KDE is a well-known, powerful and highly customizable desktop environment, designed to
offer Linux desktop users absolute control over their desktop.
 The latest release in the KDE desktop series is the Plasma 5, which has brought in several
improvements and new features.
 It has come with clean and well-polished user interfaces in comparison to previous
versions, with improved readability.
It have notable components and new features include:
• Dolphin file manager
• Kwin window manager
• A converged shell
• Updated graphics stack enabling smoother graphics performance
• Modernized launchers
• Workflow improvements in the desktop notification area
• Improved support for high-density (high-DPI) display plus many other minor features

19

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux File System / File System Hierarchy Structure


 The Linux File Hierarchy Structure or the File system Hierarchy Standard (FHS) defines the
directory structure and directory contents in Unix-like operating systems.
 It is maintained by the Linux Foundation.
 In the FHS, all files and directories appear under the root directory /, even if they are
stored on different physical or virtual devices.
 Some of these directories only exist on a particular system if certain subsystems, such as
the X Window System, are installed.
 Most of these directories exist in all UNIX operating systems and are generally used in
much the same way; however, the descriptions here are those used specifically for the
FHS, and are not considered authoritative for platforms other than Linux.

20

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux Directories
 In Linux/Unix operating system everything is a file even directories are files, files are files,
and devices like mouse, keyboard, printer, etc are also files.
 We know that in a Windows-like operating system, files are stored in different folders on
different data drives like C: D: E: whereas in the Linux/Unix operating system files are
stored in a tree-like structure starting with the root directory as shown in the below
diagram.

 The main directories are –root and home

Root Directory Home Directory

The root directory is the topmost level of The home directory is a subdirectory of the root
the system drive. directory.

It is denoted by a slash '/'. It is denoted by '~' and has path "/users/username".

The admin has access to make any changes No user other than the root user can change the
in the files and settings. settings of the entire system.

The admin can create a user. Any user having a home directory cannot create a
user.

21

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

In the Linux file system, everything comes The home directory contains a particular user's data.
under the root directory.

These are the common top-level directories associated with the root directory:

Directories Description

/bin binary or executable programs.

/etc system configuration files.

/home home directory. It is the default current directory.

/opt optional or third-party software.

/tmp temporary space, typically cleared on reboot.

/usr User related programs.

/var log files.

Types of files in the Linux system.


1. General Files – It is also called ordinary files. It may be an image, video, program, or simple
text file. These types of files can be in ASCII or Binary format. It is the most commonly used
file in the Linux system.
2. Directory Files – These types of files are a warehouse for other file types. It may be a
directory file within a directory (subdirectory).
3. Device Files – In a Windows-like operating system, devices like CD-ROM, and hard drives are
represented as drive letters like F: G: H whereas in the Linux system devices are represented
as files. As for example, /dev/sda1, /dev/sda2, and so on.

22

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux File Commands

Command Description

file Determines file type.

touch Used to create a file.

rm To remove a file.

cp To copy a file.

mv To rename or to move a file.

rename To rename file.

Installing and Configuring Linux


Installing the Linux Software After resizing your existing partitions to make space for Linux, you are
ready to install the software.
Here is a brief overview of the procedure:
1. Boot the Linux installation media.
2. Run fdisk under Linux to create Linux partitions.
3. Run mke2fs and mkswap to create Linux filesystems and swap space.
4. Install the Linux software and configure it.
5. Finally, either install the LILO boot loader on your hard drive, or create a boot floppy in
order to boot your new Linux system. docstore.mik.ua/orelly/linux/run/ch03_01.htm

23

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

File access permissions in Linux


Linux is a multi-user operating system, so it has security to prevent people from accessing each
other’s confidential files.
First, you must think of those nine characters as three sets of three characters (see the box at
the bottom). Each of the three “rwx” characters refers to a different operation you can perform
on the file.

--- --- ---

rwx rwx rwx

user group other

Read, write, and execute.

Letters Definition

‘r’ “read” the file’s contents.

‘w’ “write”, or modify, the file’s contents.

‘x’ “execute” the file. This permission is given only if the file is a program.

Symbols: `+`, `-` and `=`

Operators Definition

`+` Add permissions

`-` Remove permissions

`=` Set the permissions to the specified values

24

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux System Administration


 Linux is a major strength in computing technology. Most web servers, mobile phones,
personal computers, supercomputers, and cloud servers are powered by Linux.

 The job of a Linux systems administrator is to manage the operations of a computer


system like maintaining, enhancing, creating user accounts/reports, and taking backups
using Linux tools and command-line interface tools.

 Most computing devices are powered by Linux because of its high stability, high security,
and open-source environment.

There are some of the things that a Linux system administrator should know and understand:

1.Linux File Systems


A Linux system administrator should have a solid knowledge and understanding of the various
Linux file systems used by Linux .

Understanding the difference between these file systems is important so that one can easily
perform tasks and partition disks or configure Linux file system permissions.

2.File System Hierarchy


The Linux File System Hierarchy (FHS) tells us about the location and structure of directories and
files on a Linux system.

3.Managing Root/Super User


The root user is the most powerful user on a Linux System because it has access to all the
system files and directories. So, it is important for maintaining system security.

4.Basic Bash Command


The default shell of Linux is Bash, and it is used for executing commands on the command-line
interface. A Linux system administrator should have a basic understanding of the command of
bash to perform tasks.

*******END OF MODULE 2*******

25

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Module III
Linux Commands
date, time, who, echo, man, info, cal, pwd, more, less, head, tail, mkdir,cd, cp, mv, rm, touch, sort,
wc, cut, cat with options, ls with options ,grep with options, chmod, diff, mounting the file system,
command line processing etc. Types of editors in Linux, Introduction to vi editor, modes in vi
editor, common vi editor commands for open a file, save a file, delete a file, quit a file etc

26

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Linux Commands
Date Command
The date command is used to display date, time, time zone, and more.
 Syntax: date
Output:

Time Command
The time command is used to display the time to execute a command.
 Syntax: time
Output:

Who Command
who command is used to find out the following information :
1. Time of last system boot
2. Current run level of the system
3. List of logged in users and more.
 Syntax : $who [options] [filename]
Echo Command
The echo command in Linux is a built-in command that allows users to display lines of text or
strings that are passed as arguments.
 Syntax: echo [string]
Example: If we want to display “MACAS”. We use the following command.
 echo "MACAS"
Man Command
man command in Linux is used to display the user manual of any command that we can run on
the terminal. It provides a detailed view of the command which includes NAME, SYNOPSIS,
DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS, FILES, VERSIONS, EXAMPLES,
AUTHORS and SEE ALSO.
 Syntax : $ man [COMMAND NAME]

27

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

 Example: $ man printf


Info Command
infocommand reads documentation in the info format. It will give detailed information for a
command when compared with the man page.
 Syntax: info [OPTION]
Example : -w Command : It print physical location of Info file.

 info -w cvs

Cal Command

cal command is a calendar command in Linux which is used to see the calendar of a specific
month or a whole year

 Syntax: cal [ [ month ] year]


 Example : cal jun 2023
Pwd Command

pwd stands for Print Working Directory. It prints the path of the working directory, starting from
the root.

 Syntax: pwd [OPTIONS]

Example:

 pwd -L: Prints the symbolic path.


 pwd -P: Prints the actual path.
More Command

more command is used to view the text files in the command prompt, displaying one screen at a
time in case the file is large (For example log files).

 Syntax: more [-options] [file_name]

 Example: more -d sample.txt

28

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Less Command

Less command is a Linux utility that can be used to read the contents of a text file one page (one
screen) at a time. It has faster access because if a file is large, it doesn’t access the complete file,
but accesses it page by page.

 Syntax: less [options] filename

 Example: less -p "sample.txt"

Head Command
The head command, as the name implies, print the top N number of data of the given input. By
default, it prints the first 10 lines of the specified files
 Syntax: head [OPTION]... [FILE]...
 Example: head state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Tail Command
The tail command, as the name implies, print the last N number of data of the given input. By
default it prints the last 10 lines of the specified files.
 Syntax: tail [OPTION]... [FILE]...
 Example:$ tail state.txt
Odisha
Punjab
Rajasthan
Sikkim

29

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Mkdir command

mkdir command in Linux allows the user to create directories (also referred to as folders in some
operating systems). This command can create multiple directories at once as well as set the
permissions for the directories.

Syntax: mkdir [options...] [directories ...]


example: mkdir -p [mydirectory]

cd command
The cd command in Linux stands for change directory. It is used to change the current directory of
the terminal. The terminal, by default, opens the home directory.
Example

cd /

To go to the root directory, we input / as the argument.

cd

We do not provide any arguments to the cd command to go to the home directory.

cd . .

To shift one level above the current directory, we input .. as the argument.

cd -

To go to the previous directory, we use - as our argument.

30

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

cd /folder/subfolder

Cp command
Linux/Unix’s cp command copies files and directories from a source to a destination.
 Syntax: $ cp [options] source destination
 Example : $ cp a.txt b.txt
Mv commands
As its name suggests this command is used to rename file directories and move files from one
location to another within a file system.

Two Distinct Functions of `mv` Command


 1) Renaming a file or directory.
 2) Moving a file or directory to another location
 Syntax: mv [options(s)] [source_file_name(s)] [Destination_file_name]
 Example: mv [source_file_name(s)] [Destination_file_name]
Rm command
rm stands for remove here. rm command is used to remove objects such as files, directories,
symbolic links and so on from the file system
 syntax : rm [OPTION]... FILE...
 Example : $ rm a.txt
Touch command
touch command is a way to create empty files (there are some other mehtods also). You can
update the modification and access time of each file with the help of touch command.
 Syntax: touch <filename>
 Example: touch myfile1
sort command
The 'sort' command sorts the file content in an alphabetical order.
 Syntax: sort <fileName>
 Example: sort weeks.txt

31

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

wc Command

Linux wc command helps in counting the lines, words, and characters in a file. It displays the
number of lines, number of characters, and the number of words in a file.

 Syntax: wc <file name>


 Example : wc exm.txt

cut Command

Linux cut command is useful for selecting a specific column of a file. It is used to cut a specific
sections by byte position, character, and field and writes them to standard output. It cuts a line
and extracts the text data.

 Syntax : cut -d- -f(columnNumber) <fileName>


 Example : cut -d- -f2 marks.txt
cut -d- -f1 marks.txt

32

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Cat command

Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives
its content as output. It helps us to create, view, and concatenate files. So let us see some
frequently used cat command options.

Option 1) To view a single file


 Syntax: cat file_name
 Example: If our file_name = jayesh.txt
 cat jayesh.txt

Option 2) To view multiple files


 Syntax: cat file_name1 file_name2
 Example: If we have two files , file1 and file2.
 cat file1 file2

Option 3) Create a file and add content


 Syntax: cat > newfile_name
 Example: If we want to create a newfile_name = jayesh1.
 cat > jayesh1

Option 4) Copy the contents of one file to another file.


 Syntax: $cat [filename-whose-contents-is-to-be-copied] > [destination-filename]
 Output The content will be copied in destination file

Option 5) Cat command can append the contents of one file to the end of another file.
 Syntax: cat file_name1 >> file_name2
 Example: cat file1 >> file2
ls command

 In Linux, the command "ls" is one of the most commonly used. It's used to display a list of
files and sub-directories in the current directory.
 The 'ls' command is used to list files and directories
 The contents of your current working directory, which is just a technical way of stating the
directory that your terminal is presently in, will be listed if you run the "ls" command
without any further options.

33

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Option 1: ls - Display the hidden files and directories


Option 2: ls -a Use the -a option of the ls command to show hidden files and directories in the
current directory.The files that start with the dot are hidden (.). The current directory (.) as well as
the parent directory (..) are displayed by "ls -a".
Option 3: ls –l Display complete information about the files
The "ls -l" option displays the contents of the current directory in a long listing format, one per
line. The line begin with the file or directory permission, owner and group name, file size,
created/modified date and time, file/folder name as some of the attributes.
Option 4: ls –i Display File Index Number
For internal purposes, you may need to know the index number of a file. To display the index
number, use the "ls -i" option. You can remove files with special characters in their names by using
the index number.
Option 5: ls -tView last edited file
The most recently modified file is displayed first as the file is sorted by modification time. Use the
ls and head commands together to access the most recently edited file in the current directory.
grep command

The grep filter searches a file for a particular pattern of characters, and displays all lines that
contain that pattern. The pattern that is searched in the file is referred to as the regular
expression (grep stands for global search for regular expression and print out).
Syntax: grep [options] pattern [files]
Option 1. Case insensitive search : The -i option enables to search for a string case insensitively
in the given file. It matches the words like “UNIX”, “Unix”, “unix”.
$grep -i "UNix" geekfile.txt
Option 2. Displaying the count of number of matches : We can find the number of lines that
matches the given string/pattern
$grep -c "unix" geekfile.txt
Option 3. Display the file names that matches the pattern : We can just display the files that
contains the given string/pattern.
$grep -l "unix" *
or
$grep -l "unix" f1.txt f2.txt f3.xt f4.txt

34

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Option 4. Checking for the whole words in a file : By default, grep matches the given
string/pattern even if it is found as a substring in a file. The -w option to grep makes it match
only the whole words.
$ grep -w "unix" geekfile.txt
Option 5. Displaying only the matched pattern : By default, grep displays the entire line which
has the matched string. We can make the grep to display only the matched string by using the -o
option.
$ grep -o "unix" geekfile.txt
Chmod command

 In Unix operating systems, the chmod command is used to change the access mode of a
file. The name is an abbreviation of change mode.
 Which states that every file and directory has a set of permissions that control the
permissions like who can read, write or execute the file. In this the permissions have
three categories: read, write, and execute simultaneously represented by `r`, `w` and `x`.
These letters combine together to form a specific permission for a group of users.
 The `chmod` command is used to modify this permission so that it can grant or restrict
access to directories and files. Let’s have a look at the syntax and options for the `chmod`
command in Linux Operating System.

Syntax: chmod <options> <permissions> <file name>


Example : chmod u=rw,go=rw Demo.txt
To set the permission of a file, execute a permission statement with the chmod command. For
example, we want to set the read and write permission for all users and groups of file 'Demo.txt.'
We have to pass the "u=rw,go=rw Demo.txt" permission statement with chmod command.

Diff command
diff stands for difference. This command is used to display the differences in the files by
comparing the files line by line. Unlike its fellow members, cmp and comm, it tells us which lines
in one file have is to be changed to make the two files identical.
 Syntax : diff File1 File2
 Example: $ diff a.txt b.txt

35

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Mounting the File System


 All files in a Linux filesystem are arranged in form of a big tree rooted at ‘/‘.
 These files can be spread out on various devices based on your partition
table, initially your parent directory is mounted(i.e attached) to this tree at ‘/‘,
others can be mounted manually using GUI interface(if available) or
using mount command.
 mount command is used to mount the filesystem found on a device to big
tree structure(Linux filesystem) rooted at ‘/‘. Conversely, another
command umount can be used to detach these devices from the Tree.
 Syntax:
 mount -t type device dir

Command Line Processing


 The Linux command line is a text interface to your computer. Often referred to as the shell,
terminal, console, prompt or various other names, it can give the appearance of being
complex and confusing to use. Yet the ability to copy and paste commands from a website
 The shell is the command interpreter on the Linux systems. It the program that interacts
with the users in the terminal emulation window. Shell commands are instructions that
instruct the system to do some action.
 Each line that the shell reads from the standard input or a script is called a pipeline; it
contains one or more commands separated by zero or more pipe characters (|). For each
pipeline it reads, the shell breaks it up into commands, sets up the I/O for the pipeline,
 Steps in command line processing is shown in the figure

36

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

37

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Types of Text Editors in Linux


Linux text editors can be used for editing text files, writing codes, updating user instruction
files, and more.

A Linux system supports multiple text editors. There are two types of text editors in Linux, which
are given below:

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


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

A text editor plays an important role while coding. So, it is important to select the best text editor.
A text editor should not only be simple but also functional and should be good to work with.

A text editor with IDE features is considered as a good text editor.

The following are some important text editors in linux


1.Vi/VIM editor
Vim editor is one of the most used and powerful command-line based editor of the Linux system.
By default, it is supported by most Linux distros. It has enhanced functionalities of the old Unix Vi
editor.
2. Nano editor
Nano is a straight forward editor. It is designed for both beginners and advanced users. It has
many customization features.
3. Gedit editor
Gedit editor is the default editor for the GNOME desktop environment. When we open a file, it
will open with the Gedit editor. It provides straightforward functionalities like any basic text
editor. It is a lightweight editor with a straight forward user interface.
4. Sublime Text
The sublime text editor is also one of the most popular IDE-based text editors. It is used as a
development environment tool more than a text editor. It has several features to support many
programming and mark-up languages.
5. VSCode Editor

38

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

VSCode editor is a modern and widely used text editor. It is built by Microsoft and has support for
Linux, Mac and Windows OS. It facilitates with many powerful features to support many
programming languages and markup language.

Introduction to vi editor
The default editor that comes with the 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. The advanced version of the vi editor is the vim editor.

The vi editor has two modes:

o Command Mode: In command mode, actions are taken on the file. The vi editor starts in
command mode. Here, the typed words will act as commands in vi editor. To pass a
command, you need to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will
take you to the command mode from insert mode.

By default, the vi editor starts in command mode. To enter text, you have to be in insert mode,
just type 'i' and you'll be in insert mode. Although, after typing i nothing will appear on the screen
but you'll be in insert mode. Now you can type anything.

To exit from insert mode press Esc key, you'll be directed to command mode.

Modes of Vi Editors
1.Command Mode

This is what you'll see when you'll press enter after the above command. If you'll start typing,
nothing will appear as you are in command mode. By default vi opens in command mode.

39

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Look at the above snapshot, it is blank as it is a new file. To start typing, you have to move to the
insert mode. At the end of the terminal window, directory name and file name are displayed.

2.Insert mode

To move to the insert mode press i. Although, there are other commands also to move to insert
mode which we'll study in next page.

Look at the above snapshot, after pressing i we have entered into insert mode. Now we can write
anything. To move to the next line press enter.

Once you have done with your typing, press esc key to return to the command mode.

Commands in Vi Editor
Open VI editor File
To open vi editors, we just need to type the command mentioned below.

vi [file_name]

Here, [file_name] = “macas” this is the file name we want to create or to open the pre-existing
file.

Creating a new file with `file_name` = macas


vi macas.txt

40

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

2.Save a file in Vi Editor

You can save and quit vi editor from command mode. Before writing save or quit command you
have to press colon (:). Colon allows you to give instructions to vi.

To exit from vi, first ensure that you are in command mode. Now, type :wq and press enter. It will
save and quit vi.

3.Delete a file in Vi Editor


You can delete or remove characters in different ways. r key is used to replace one single
character. The r key will bring you in insert mode for just one key press and then you'll be directed
to command mode.
X :-The command x is used to delete current character.
dd:-The command dd deletes current line completely.
D:-The command D is used to delete from current character to the end of the line.
dG:-The command dG is used to delete from current line to the end line of the file.

4.Quit A file in Vi Editor

o step1. Switch to command mode by pressing the Esc key.


o step2. Press : (colon) to open the prompt bar in the bottom left corner of the window.
o Step3. Type x after the colon and hit Enter. This will save the changes and exit the current
file

*******END OF MODULE 3*******

41

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Module IV
Shell Programming
Introduction to Linux Shell and Shell Scripting, types of shells in Linux, steps in creating a shell
script, write and run shell scripts, shell variables and printing, deleting shell variables, script
permissions and names, scripting guidelines, adding shell comments, shell variables, constants,
operators, conditional statements, looping statements, using arrays, shell functions,files, shell
built-in functions

42

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Introduction to Linux Shell and Shell Scripting

 If we are using any major operating system, we are indirectly interacting with the shell.
 While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting
with the shell by using the terminal.
 Before understanding shell scripting we have to get familiar with the following
terminologies:

1. Kernel
2. Shell
3. Terminal
1.What is Kernel?
The kernel is a computer program that is the core of a computer’s operating system, with
complete control over everything in the system. It manages the following resources of the Linux
system –

 File management
 Process management
 I/O management
 Memory management
 Device management etc.

2.What is Shell?
 A shell is a special user program that provides an interface for the user to use operating
system services.

 Shell accepts human-readable commands from users 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.

43

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

3.What is a terminal?
 A program which is responsible for providing an interface to a user so that he/she can
access the shell.

 It basically allows users to enter commands and see the output of those commands in a
text-based interface.

 Large scripts that are written to automate and perform complex tasks are executed in
the terminal.

 To access the terminal, simply search in search box “terminal” and double-click it.

44

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Shell Scripting
Usually, shells are interactive, which means they accept commands as input from users and
execute them. However, sometimes we want to execute a bunch of commands routinely, so we
have to type in all commands each time in the terminal.

 As a shell can also take commands as input from file, we can write these commands in a
file and can execute them in shell to avoid this repetitive work.
 These files are called Shell Scripts or Shell Programs.
 Shell scripts are similar to the batch file in MS-DOS.
 Each shell script is saved with `.sh` file extension e.g., myscript.sh
 A shell script has syntax just like any other programming language.
A shell script comprises the following elements –

 Shell Keywords – if, else, break etc.


 Shell commands – cd, ls, echo, pwd, touch etc.
 Functions
 Control flow – if..then..else, case and shell loops etc.

Types of Shell in Linux

Shell is broadly classified into two categories –

a) Command Line Shell


b) Graphical shell

a)Command Line Shell


 Shell can be accessed by users using a command line interface.
 A special program called Terminal in Linux/macOS, or Command Prompt in Windows OS
is provided to type in the human-readable commands such as “cat”, “ls” etc. and then it
is being executed.
 The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4
system looks like this –

45

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

b)Graphical Shells
Graphical shells provide means for manipulating programs based on the graphical user interface
(GUI), by allowing for operations such as opening, closing, moving, and resizing windows, as well
as switching focus between windows.

46

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Steps In Creating A Shell Script

Shell Scripts are written using text editors. On your Linux system, open a text editor program,
open a new file to begin typing a shell script or shell programming, then give the shell permission
to execute your shell script and put your script at the location from where the shell can find it.

Let us understand the steps in creating a Shell Script:

1. Create a file using a vi editor (or any other editor). Name script file with extension .sh
2. Start the script with #! /bin/sh
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh

Example

47

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Comments in the shell script


Any line which starts with “#” in the shell script is treated as a comment and is ignored by the
shell during execution, except the shebang line, which we will see later in this article. Let’s see
an example.

# This is a comment

echo Testing comments in shell script

Variables in Shell Script


Shell scripts support the use of variables, and we need not define a variable’s type during its
declaration. There are two types of variables:

 System Defined variables


 User-Defined Variables.

System-defined variables, also called environment variables, are generally Capitalised. You can
view all the current environment variables using the printenv command.

User-Defined variables are set by the user, and they exist only during script execution. You can
define a variable by simply typing its name and assigning a value with = sign and access a
variable by adding a $ before the variable name. Variables are demonstrated in the following
example script.

# Accessing an Environment Variable

echo $USER

# Creating and accessing User defined Variable

variable_name="Geeksforgeeks"

echo $variable_name

48

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Deleting Shell Variables

The unset command directs a shell to delete a variable and its stored data from list of
variables. It can be used as follows:

var1="Devil"
var2=23
echo $var1 $var2
unset var1
echo $var1 $var2
Output:
DEVIL 23

23

Script Permissions and Names

File permissions can be described as who, what, and which activities can be done to a file or
directory.
 who refers to users, groups, or others
 what means to add, delete and set
 which means read, write, and execute
Manage file permissions
To manage file permissions, we have a command called chmod which we can use to change the
permission of files and directories.
Syntax:
chmod whowhatwhich File|directory
 who is u(user) , g(group) , o(other)
 what is to +(add) ,-(remove) ,+(set)
 which is r (read), w(write), x(execute)
Let’s see an example: –
Suppose you want to remove read and write permission of group and others from the file
chmod go-rw <FILE> (can be any file name)

49

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Scripting Guidelines

1.Script Naming

Like other executables, shell script file names should not include an extension.

2.Script Location

For ease of execution, scripts should be placed in a directory listed in the user’s PATH.
The ~/bin directory is a good location for personal scripts .

3.Formatting and Visual Style

Good visual layout makes scripts easier to read and understand. It’s important to make formatting
consistent so it creates a reliable visual language for the code.

4.Line Length

In order to improve readability and to display properly in small terminal windows, line length
should be limited to 80 characters.

5.Indentation

Indention should be done with spaces and never with tab characters.

6.Constant, Variable and Function Names

Constant names should be written in all caps. Variable and function names should be written in all
lowercase.

Adding Shell Comments


Any line which starts with “#” in the shell script is treated as a comment and is ignored by the
shell during execution, except the shebang line, which we will see later in this article. Let’s see
an example.

# This is a comment

echo Testing comments in shell script

50

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Variables in Shell
1) Local Variable:
Variables which are specific to the current instance of shell. They are basically used within the
shell, but not available for the program or other shells that are started from within the current
shell.

For example:
`name=Jayesh`

In this case the local variable is (name) with the value of Jayesh. Local variables is temporary
storage of data within a shell script.

2) Environment Variable:

These variables are commonly used to configure the behavior script and programs that are run
by shell. Environment variables are only created once, after which they can be used by any user.

For example:
`export PATH=/usr/local/bin:$PATH` would add `/usr/local/bin` to the beginning of the shell’s
search path for executable programs.

3) Shell Variables:

Variables that are set by shell itself and help shell to work with functions correctly. It contains
both, which means it has both, some variables are Environment variable, and some are Local
Variables.

For example:
`$PWD` = Stores working directory

`$HOME` = Stores user’s home directory

`$SHELL` = Stores the path to the shell program that is being used.

51

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Constants in shell script

 A constant is just like a variable except for the fact that its value does not change during
the execution of your script.
 This makes sense in scripts for which you have to define the total amount of months in a
year for example. This is a number that is not likely to change anytime soon.

Example: TOTAL_MONTHS =12

 TOTAL_MONTHS constant is written in all caps, this is actually just a convention and
nothing prevents you from changing its value. Using all caps does not enforce a readonly
value in bash so if you would like to change TOTAL_MONTHS to 11 you are free to do so

Shell Basic Operators


There are various operators supported by each shell.

1. Arithmetic Operators

2. Relational Operators
3. Boolean Operators
4. String Operators
5. File Test Operators
1.Arithmetic Operators

The following arithmetic operators are supported by Shell.

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example

+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30

- (Subtraction) Subtracts right hand operand from left hand `expr $a - $b` will give -10
operand

52

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give
200

/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2

% (Modulus) Divides left hand operand by right hand operand `expr $b % $a` will give 0
and returns remainder

= (Assignment) a = $b would assign value


Assigns right operand in left operand
of b into a

== (Equality) Compares two numbers, if both are same then [ $a == $b ] would return
returns true. false.

!= (Not Equality) Compares two numbers, if both are different then [ $a != $b ] would return
returns true. true.

It is very important to understand that all the conditional expressions should be inside square
braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is
incorrect.

2.Relational Operators

Shell supports the following relational operators that are specific to numeric values. These
operators do not work for string values unless their value is numeric.

For example, following operators will work to check a relation between 10 and 20 as well as in
between "10" and "20" but not in between "ten" and "twenty".

Assume variable a holds 10 and variable b holds 20 then –

53

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Operator Description Example

-eq Checks if the value of two operands are equal or not; if yes, [ $a -eq $b ] is not true.
then the condition becomes true.

-ne Checks if the value of two operands are equal or not; if values
[ $a -ne $b ] is true.
are not equal, then the condition becomes true.

-gt Checks if the value of left operand is greater than the value of
[ $a -gt $b ] is not true.
right operand; if yes, then the condition becomes true.

-lt Checks if the value of left operand is less than the value of
[ $a -lt $b ] is true.
right operand; if yes, then the condition becomes true.

-ge Checks if the value of left operand is greater than or equal to


the value of right operand; if yes, then the condition becomes [ $a -ge $b ] is not true.
true.

-le Checks if the value of left operand is less than or equal to the
value of right operand; if yes, then the condition becomes [ $a -le $b ] is true.
true.

It is very important to understand that all the conditional expressions should be placed inside
square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is
incorrect.

3.Boolean Operators

The following Boolean operators are supported by the Shell.

Assume variable a holds 10 and variable b holds 20 then −

54

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Operator Description Example

! This is logical negation. This inverts a true condition


[ ! false ] is true.
into false and vice versa.

-o This is logical OR. If one of the operands is true, then [ $a -lt 20 -o $b -gt 100 ] is true.
the condition becomes true.

-a This is logical AND. If both the operands are true,


[ $a -lt 20 -a $b -gt 100 ] is false.
then the condition becomes true otherwise false.

4.String Operators

The following string operators are supported by Shell.

Assume variable a holds "abc" and variable b holds "efg" then −

Operator Description Example

= Checks if the value of two operands are equal or not; if [ $a = $b ] is not true.
yes, then the condition becomes true.

!= Checks if the value of two operands are equal or not; if [ $a != $b ] is true.


values are not equal then the condition becomes true.

-z Checks if the given string operand size is zero; if it is zero [ -z $a ] is not true.
length, then it returns true.

-n Checks if the given string operand size is non-zero; if it is [ -n $a ] is not false.


nonzero length, then it returns true.

55

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

str Checks if str is not the empty string; if it is empty, then it [ $a ] is not false.
returns false.

5.File Test Operators

We have a few operators that can be used to test various properties associated with a Unix file.

Assume a variable file holds an existing file name "test" the size of which is 100 bytes and
has read, write and execute permission on −

Show Examples

Operator Description Example

-b file Checks if file is a block special file; if yes, then the [ -b $file ] is false.
condition becomes true.

-c file Checks if file is a character special file; if yes, then the [ -c $file ] is false.
condition becomes true.

-d file Checks if file is a directory; if yes, then the condition [ -d $file ] is not true.
becomes true.

-f file Checks if file is an ordinary file as opposed to a directory [ -f $file ] is true.


or special file; if yes, then the condition becomes true.

-g file Checks if file has its set group ID (SGID) bit set; if yes, then [ -g $file ] is false.
the condition becomes true.

-k file Checks if file has its sticky bit set; if yes, then the [ -k $file ] is false.
condition becomes true.

-p file Checks if file is a named pipe; if yes, then the condition [ -p $file ] is false.

56

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

becomes true.

-t file Checks if file descriptor is open and associated with a [ -t $file ] is false.
terminal; if yes, then the condition becomes true.

-u file Checks if file has its Set User ID (SUID) bit set; if yes, then [ -u $file ] is false.
the condition becomes true.

-r file Checks if file is readable; if yes, then the condition [ -r $file ] is true.
becomes true.

-w file Checks if file is writable; if yes, then the condition [ -w $file ] is true.
becomes true.

-x file Checks if file is executable; if yes, then the condition [ -x $file ] is true.
becomes true.

-s file Checks if file has size greater than 0; if yes, then condition [ -s $file ] is true.
becomes true.

-e file Checks if file exists; is true even if file is a directory but [ -e $file ] is true.
exists.

Conditional Statements
Conditional Statements: There are total 5 conditional statements which can be used in bash
programming
1. if statement
2. if-else statement
3. if..elif..else..fi statement (Else If ladder)
4. if..then..else..if..then..fi..fi..(Nested if)

57

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

5. switch statement
Their description with syntax is as follows:

1.if statement
This block will process if specified condition is true.
Syntax:
if [ expression ]
then
statement
fi
Example:
if [ $a != $b ]
then
echo "a is not equal to b"
fi
2.if-else statement
If specified condition is not true in if part then else part will be execute.
Syntax
if [ expression ]
then
statement1
else
statement2
fi
Example:
if [ $a == $b ]
then
#If they are equal then print this
echo "a is equal to b"
else
#else print this
echo "a is not equal to b"

58

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

fi

3.if..elif..else..fi statement (Else If ladder)


To use multiple conditions in one if-else block, then elif keyword is used in shell.
If expression1 is true then it executes statement 1 and 2, and this process continues.
If none of the condition is true then it processes else part.
Syntax
if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi
4.if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies then it again checks another
condition.
In the syntax, if expression1 is false then it processes else part, and again expression2 will be
check.
Syntax:
if [ expression1 ]
then
statement1

59

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
5.switch statement
case statement works as a switch statement if specified value match with the pattern then it will
execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is
executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
Esac

Looping Statements
Looping Statements in Shell Scripting: There are total 3 looping statements that can be used in
bash programming
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:

60

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

1.while statement
Here the command is evaluated and based on the resulting loop will execute, if the command is
raise to false then the loop will be terminated that
while <condition>
do

<command 1>
<command 2>
<etc>
done
Example:

2.for statement
The for loop operates on lists of items. It repeats a set of commands for every item in a list.

Syntax:
for <var> in <value1 value2 ... valuen>
do
<command 1>
<command 2>
<etc>
done
3.until statement
The until loop is executed as many times as the condition/command evaluates too false. The
loop terminates when the condition/command becomes true.
Syntax:
until <condition>
do
<command 1>
<command 2>

61

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

<etc>
done

Arrays in Shell Script


Variables store single data elements. Arrays, on the other hand, can store a virtually unlimited
number of data elements. When working with a large amount of data, variables can prove to be
very inefficient and it’s very helpful to get hands-on with arrays

There are two types of arrays that we can work with, in shell scripts.

 Indexed Arrays - Store elements with an index starting from 0


 Associative Arrays - Store elements in key-value pairs
Declaring Arrays:
assoc_array[key]=value
OR
indexed_array[0]=value
Array Operations
1. Accessing Array Elements Individually

Since we know that each data point is being indexed individually, we can access all the array
elements by specifying the array index as shown below:

assoc_array[element1]="Hello World"
echo ${assoc_array[element1]}
2. Reading Array Elements Sequentially
This is going to be an easy task if you know for loops already.
index_array=(1 2 3 4 5 6 7 8 9 0)
for i in ${index_array[@]}
do
echo $i
done
3. Access All Elements of an Array
echo ${assoc_array[@]}

62

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

Function
A function is a collection of statements that execute a specified task. Its main goal is to break
down a complicated procedure into simpler subroutines that can subsequently be used to
accomplish the more complex routine.For the following reasons, functions are popular:

 Assist with code reuse.


 Enhance the program’s readability.
 Modularize the software.
 Allow for easy maintenance.
The basic structure of a function in shell scripting looks as follows:

function_name(){

// body of the function

Types of Functions
The functions in shell scripting can be boxed into a number of categories.

1. The functions that return a value to the caller.

The return keyword is used by the functions for this purpose.

The following is one such function used to calculate the average of the given numbers.

find_avg()
{
len=$#
sum=0
for x in "$@"
do
sum=$((sum + x))
done

63

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

avg=$((sum/len))
return $avg
}
find_avg 30 40 50 60
printf "%f" "$?"
printf "\n"
Output:

2. The functions that terminate the shell using the exit keyword.

is_odd(){
x=$1
if [ $((x%2)) == 0 ]; then
echo "Invalid Input"
exit 1
else
echo "Number is Odd"
fi
}
is_odd 64
Output:

3. The functions that alter the value of a variable or variables.

a=1
increment(){
a=$((a+1))
return
}

64

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

increment
echo "$a"

Output:

4. The functions that echo output to the standard output.

hello_world()
{
echo "Hello World"
return
}
hello_world
Output:

Files in Shell

 A file with .sh extension is a scripting language commands file that contains computer
program to be run by Unix shell.

 It can contain a series of commands that run sequentially to carry out operations such as
files processing, execution of programs and other such tasks.

 These are executed from the command line interface by user or in batch to carry out
multiple operations at the same time.

 Script files can be opened in text editors like Notepad, Notepad++, Vim, Apple Terminal
and other similar applications on Windows, MacOS and Linux O

65

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

How to run file?

The SH files usually run on Linux, even in Windows you need to connect with a Linux terminal
using softwares such as Putty to run the sh files. Following are the steps to run an SH file on a
Linux terminal.

1. Open the Linux terminal and go to the directory where the SH file is located.

2. By Using chmod command, set execute permission on your script (if not set already).
3. Run script using one of the following

1. ./filename.sh
2. sh filename.sh
3. bash script-name-here.sh

Shell Built-In Functions


The Korn shell provides access to the standard set of functions. They are called using C function
call syntax.

Sr.No. Function & Description

1 abs
Absolute value

2 log
Natural logarithm

3 acos
Arc cosine

4 sin
Sine

5 asin
Arc sine

66

Downloaded by Akhila P ([email protected])


lOMoARcPSD|19230806

FOSS MACAS

6 sinh
Hyperbolic sine

7 cos
Cosine

8 sqrt
Square root

9 cosh
Hyperbolic cosine

10 tan
Tangent

11 exp
Exponential function

12 tanh
Hyperbolic tangent

13 int
Integer part of floating-point number

*******END OF MODULE 4*******

67

Downloaded by Akhila P ([email protected])

You might also like