foss-full-notes
foss-full-notes
FOSS MACAS
Name : ……………………………………………………………………………………………
FOSS MACAS
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
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
FOSS MACAS
Security
Affordability
Transparent
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
FOSS MACAS
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.
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.
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
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.
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
FOSS MACAS
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.
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.
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.
Often, free software has the same features as its high-priced proprietary counterparts – andthat is
only one of the many advantages:
FOSS MACAS
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.
FOSS MACAS
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.
FOSS MACAS
10
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).
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.
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
11
FOSS MACAS
12
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.
13
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
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
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.
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
FOSS MACAS
Architecture of Linux
1.The Kernel
2.System Library
3.Hardware layer
4.System
5.Shell utility.
1. Kernel:-
There are some of the important kernel types which are mentioned below:
16
FOSS MACAS
o Monolithic Kernel
o Micro kernels
o Exo kernels
o Hybrid kernels
2. System Libraries:-
4. Hardware layer:-
Linux operating system contains a hardware layer that consists of several peripheral
devices like CPU, HDD, and RAM.
5. Shell:-
17
FOSS MACAS
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.
18
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
FOSS MACAS
20
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 root directory is the topmost level of The home directory is a subdirectory of the root
the system drive. directory.
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
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
22
FOSS MACAS
Command Description
rm To remove a file.
cp To copy a file.
23
FOSS MACAS
Letters Definition
‘x’ “execute” the file. This permission is given only if the file is a program.
Operators Definition
24
FOSS MACAS
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:
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.
25
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
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
FOSS MACAS
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
pwd stands for Print Working Directory. It prints the path of the working directory, starting from
the root.
Example:
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).
28
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.
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
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.
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 /
cd
cd . .
To shift one level above the current directory, we input .. as the argument.
cd -
30
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.
31
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.
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.
32
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 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
FOSS MACAS
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
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.
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
FOSS MACAS
36
FOSS MACAS
37
FOSS MACAS
A Linux system supports multiple text editors. There are two types of text editors in Linux, which
are given below:
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.
38
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.
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
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.
40
FOSS MACAS
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.
41
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
FOSS MACAS
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
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
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 –
45
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
FOSS MACAS
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.
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
FOSS MACAS
# This is a comment
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.
echo $USER
variable_name="Geeksforgeeks"
echo $variable_name
48
FOSS MACAS
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
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
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 .
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.
Constant names should be written in all caps. Variable and function names should be written in all
lowercase.
# This is a comment
50
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
`$SHELL` = Stores the path to the shell program that is being used.
51
FOSS MACAS
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.
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
1. Arithmetic Operators
2. Relational Operators
3. Boolean Operators
4. String Operators
5. File Test Operators
1.Arithmetic Operators
+ (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
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
== (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".
53
FOSS MACAS
-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.
-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
54
FOSS MACAS
-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.
4.String Operators
= Checks if the value of two operands are equal or not; if [ $a = $b ] is not true.
yes, 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.
55
FOSS MACAS
str Checks if str is not the empty string; if it is empty, then it [ $a ] is not false.
returns false.
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
-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.
-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
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
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
FOSS MACAS
fi
59
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
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
FOSS MACAS
<etc>
done
There are two types of arrays that we can work with, in shell scripts.
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
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:
function_name(){
Types of Functions
The functions in shell scripting can be boxed into a number of categories.
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
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:
a=1
increment(){
a=$((a+1))
return
}
64
FOSS MACAS
increment
echo "$a"
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
FOSS MACAS
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
1 abs
Absolute value
2 log
Natural logarithm
3 acos
Arc cosine
4 sin
Sine
5 asin
Arc sine
66
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
67