Open Source Software (Linux Administration) : Course Code - CSE0002
Open Source Software (Linux Administration) : Course Code - CSE0002
(LINUX ADMINISTRATION)
• In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.
• We need a system which can act as an intermediary and manage all the processes and resources
present in the system.
Operating System Definition and Function
1.Process Management
2.Process Synchronization
3.Memory Management
4.CPU Scheduling
5.File Management
6.Security
Types of Operating Systems (OS)
What is an Open-Source Operating System?
• The term "open source" refers to computer software or applications where the
owners or copyright holders enable the users or third parties to use, see, and edit
the product's source code.
• The source code of an open-source OS is publicly visible and editable. The usually
operating systems such as Apple's iOS, Microsoft's Windows, and Apple's Mac OS
are closed operating systems.
• Open-Source Software is licensed in such a way that it is permissible to produce
as many copies as you want and to use them wherever you like.
• It generally uses fewer resources than its commercial counterpart because it lacks
any code for licensing, promoting other products, authentication, attaching
advertisements, etc.
Open-source operating system
• The open-source operating system allows the use of code that is freely
distributed and available to anyone and for commercial purposes.
• Being an open-source application or program, the program source
code of an open-source OS is available.
• The user may modify or change those codes and develop new
applications according to the user requirement.
• Some basic examples of the open-source operating systems are Linux,
Open Solaris, Free RTOS, Open BDS, Free BSD, Minix, etc.
Free Software
• Open Source Software is something that you can modify as per your needs, and
share with others without any licensing violation burden.
• When we say Open Source, the source code of the software is available publicly
with Open Source licenses like GNU (GPL) which allows you to edit the source
code and distribute it.
1.Coined by the development environments around software produced by open
collaboration of software developers on the internet.
2.Later specified by the Open Source Initiative (OSI).
3.It does not explicitly state ethical values, besides those directly associated with
software development.
Advantages
• Cost: Open source software is typically free to use, modify and distribute.
• Customization: The source code of open source software is available to everyone,
allowing users to modify and customize it to suit their needs.
• Community support: Open source software often has a large community of
developers and users who contribute to its development and provide support.
• Transparency: The source code of open source software is open for everyone to
see, making it easier to identify and fix bugs and vulnerabilities.
• Flexibility: Open source software can be used on a wide range of platforms and
devices.
Disadvantages
• Support: While open source software does have a large community of developers
and users, it may not always have the same level of professional support as
commercial software.
• Compatibility: Open source software may not always be compatible with other
software applications and hardware devices.
• Security: Because the source code of open source software is available to
everyone, it may be easier for malicious actors to identify and exploit
vulnerabilities.
• Complexity: Open source software can be more complex and difficult to use than
commercial software, especially for non-technical users.
• Documentation: Open source software may not always have the same level of
documentation and user guides as commercial software.
Similarities
• Both free software and open source software have access to the source
code, allowing users to modify and improve the software.
• Both types of software often rely on a community of users and
developers to provide support and contribute to the development of the
software.
• Both free software and open source software are often distributed
under open licenses, allowing users to use, modify, and distribute the
software without restrictions.
S.No. Free Software (FS) Philosophy Open Source Software (OSS) Philosophy
In response to the restrictions of free software, the phrase “open source” was
1. It was coined by the Free Software Foundation in the 1980s.
coined in the late 1990s.
2. Software is an important part of people’s lives. Software is just software. There are no ethics associated directly with it.
3. Software freedom translates to social freedom. Ethics are to be associated with the people not with the software.
5. Every free software is open source. Every open-source software is not free software.
There are many different open-source software licenses, and some of them are
6. There is no such issue that exists in free software.
quite restricted, resulting in open-source software that is not free.
7. No restrictions are imposed on free software. Open-source software occasionally imposes some constraints on users.
Path Separator The path separator that Linux uses is The path separator that Windows uses
Slash. is backward slash.
Efficiency In the case of operations, Linux is way For operations, Windows are
more efficient than Windows. comparatively way less efficient than
Linux.
Security It is more secure than Windows OS. It provides much less security to its
users than Linux.
Uses in Hacking People generally use Linux for the Windows is not a very efficient OS for
systems that are hacking-based. hacking purposes as compared to
Linux.
Windows Linux
Windows uses different data drives like C: D: E to Unix/Linux uses a tree like a hierarchical file
stored files and folders. system.
Windows has different drives like C: D: E There are no drives in Linux
Hard drives, CD-ROMs, printers are considered as Peripherals like hard drives, CD-ROMs, printers are
devices also considered files in Linux/Unix
There are 4 types of user account types 1) There are 3 types of user account types 1) Regular,
Administrator, 2) Standard, 3) Child, 4) Guest 2) Root and 3) Service Account
Administrator user has all administrative privileges Root user is the super user and has all administrative
of computers. privileges.
Linux file naming convention is case sensitive.
In Windows, you cannot have 2 files with the same
Thus, sample and SAMPLE are 2 different files in
name in the same folder
Linux/Unix operating system.
In windows, My Documents is default home For every user /home/username directory is created
directory. which is called his home directory.
Operating System - Linux
• The LAMP stack is a popular open-source solution stack used primarily in web development.
• LAMP consists of four components necessary to establish a fully functional web development
environment. The first letters of the components' names make up the LAMP acronym:
• Linux is an operating system used to run the rest of the components.
• Apache HTTP Server is a web server software used to serve static web pages.
• MySQL is a relational database management system used for creating and managing web
databases, but also for data warehousing, application logging, e-commerce, etc.
• PHP, Perl, and Python are programming languages are used to create web applications.
• Each component represents an essential layer of the stack. Together, the components are used to
create database-driven, dynamic websites.
Advantages of LAMP Stack
su and sudo Used to change the user and work with root
Package files are the base units of software in the Linux packaging
system. Basically, it’s a compressed group of files that may comprise:
• a number of programs
• data files that support the programs
• package metadata
• package pre-installation and post-installation scripts
RPM Package Manager
RPM stands for Red Hat Package Manager. It provides the standard way to package
software for the Red Hat Enterprise Linux (RHEL) distribution and its close
relatives Fedora, CentOS, and OpenSUSE.
• Also, Linux package management systems usually consist of two types of tools:
• low-level tools to perform tasks such as installing and erasing package files
• high-level tools that carry out dependency resolution and metadata searching
• While all Red Hat-style Linux distributions use the same low-level program rpm,
the high-level tools are not the same.
Removing RPM Packages With dnf
• Unlike dnf, rpm can remove a package without removing packages that depend on
it. In other words, the rpm program doesn’t handle dependency resolution.
• To erase a program with rpm, we run the rpm command with the -e flag:
• $ sudo rpm -e util-linux
• Copy
• Usually, if other packages need the one we’re uninstalling, rpm -e will fail. Consequently, it
produces an error message. A successful uninstall produces no output.
• Still, programs in Linux are hardly stand-alone. Instead, they often rely on the presence of other
software units. Hence, the system blocks operations that would cause problems from completion
like:
• removing a package that another package depends on
• installing a package when the system needs initial software to run the package
Linux Application
• Accessing and Running Applications: cc compiler, gcc Compiler.
Multimedia in Linux: Listening to Audio, Playing video, Recording
music.
• Publishing: Open office, Working with Graphics, Printing Documents,
Displaying documents with Ghostscript and Acrobat, Using Scanners
driven by SANE.
GCC Linux
• nano hello.c
#include <stdio.h>
int main()
{
printf ("Hello World!\n");
return 0;
}
gcc hello.c -o hello
• Save the file and compile it into an executable using the
following command:
gcc hello.c -o hello
Environment Variables in Linux/Unix
2 A static web server includes a computer and the HTTP A dynamic web server also includes a computer with plenty of
(Hyper Text Transfer Protocol) software. other software, unlike an application server and database model.
3 It is called static; the web pages content won't change It is called dynamic because the application server is used to
unless the user manually changes it, and the server will update the web pages files at the server-side, and due to which, it
deliver web files as is to the web browser. can change on every call requested by the web browser.
4 Static web servers take less time to load the data. The Dynamic web server can only produce the data when it is
requested from the database. Therefore, it is time consuming and
more complicated when compared to static web servers.
Proxy Server
• Forward Proxies
• Open Proxies
• Reverse Proxies
Architecture
Search Engines
Search Engine Components
• Indexing Process
• Text acquisition
• Text transformation
• Index creation
• Query Process
• User interaction
• Ranking
• Evaluation
Examples
Search Description
Engine
Google It was originally called BackRub. It is the most popular search engine globally.
Bing It was launched in 2009 by Microsoft. It is the latest web-based search engine that also delivers
Yahoo’s results.
Ask It was launched in 1996 and was originally known as Ask Jeeves. It includes support for match,
dictionary, and conversation question.
AltaVista It was launched by Digital Equipment Corporation in 1995. Since 2003, it is powered by Yahoo
technology.
AOL.Searc It is powered by Google.
h
LYCOS It is top 5 internet portal and 13th largest online property according to Media Matrix.
Alexa It is subsidiary of Amazon and used for providing website traffic information.
Web Based Chat Services
Website Description
Facebook It was founded by Mark Zuckerberg with his college roommates at Harvard
university. Facebook lets the user to create personal profile, post status & photos,
and receive notifications.
eBuddy It is an instant messaging service. It supports multiprotocol instant messaging
clients.
Convore It offers real time web based chat system.
MeBeam It offers video based chat between the clients to create video conferencing rooms
for up to 16 people.
Yahoo! It offers PC-PC, PC-phone, Phone-to-PC, file transfer, webcam hosting, text
Messenger messaging service etc.
WhatsApp It is an instant messaging service application available on smart phones.
Gmail It offers instant chatting, sending and receiving mails, and video calling services.
Instant Messaging (IM)
Application Description
Nimbuzz It is native iPhone app. It supports voice and video chats, file sharing, and
group chats with panache.
eBuddy eBuddy IM helps to have all your buddies from multiple IM accounts in one
single list.
Imo.in It has capability to link all your IM accounts together. You can log on to all of
your IM accounts by just logging into imo.in.
MeBeam It offers video based chat between the clients to create video conferencing
rooms for up to 16 people.
Yahoo! Messenger It offers PC-PC, PC-phone, Phone-to-PC, file transfer, webcam hosting, text
messaging service etc.
GoogleTalk It is an IM by Google and one of the most widely used.
Lync Lync is an IM developed by Microsoft. It is widely used in corporate sector for
internal and external communication as well.
Video Conferencing
• Point-to-Point
• Multi-point
Video Sharing
Mailing List
• Apache is free and open-source software of web server that is used by approx 40% of websites all
over the world.
• Apache HTTP Server is its official name.
• It is developed and maintained by the Apache Software Foundation.
• Apache permits the owners of the websites for serving content over the web.
• It is the reason why it is known as a "web server."
• One of the most reliable and old versions of the Apache web server was published in 1995.
• If someone wishes to visit any website, they fill-out the name of the domain in their browser
address bar.
• The web server will bring the requested files by performing as the virtual delivery person.
Pros and Cons of Apache
• Pros:
1.Stable and reliable software.
2.Free and open-source, even for economic use.
3.Regular security patches, frequently updated.
4.Beginner-friendly, easy to configure.
5.Flexible because of the module-based structure.
6.Works out of a box with the WordPress sites.
7.Cross-platform (implements on Windows servers and Unix).
8.Easily available support and a huge community in the case of any issue.
Pros and Cons of Apache
• Cons:
1.Various performance issues on extremely heavy-traffic websites.
2.Several options of configuration can cause security susceptibility.
MySQL
MySQL :
• Database
• Table
• Column
• Row
• Redundancy
• Primary Key
• Foreign Key
• Compound Key
• Index
• Referential Integrity
MySQL Database
• MySQL is released under an open-source license. So you have nothing to pay to use it.
• MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most
expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA,
etc.
• MySQL works very quickly and works well even with large data sets.
• MySQL is very friendly to PHP, the most appreciated language for web development.
• MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a
table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8
million terabytes (TB).
• MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software
to fit their own specific environments.
Administrative MySQL Command
• USE Databasename − This will be used to select a database in the MySQL workarea.
• SHOW DATABASES − Lists out the databases that are accessible by the MySQL DBMS.
• SHOW TABLES − Shows the tables in the database once a database has been selected
with the use command.
• SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key
information, whether NULL is permitted, defaults, and other information for a table.
• SHOW INDEX FROM tablename − Presents the details of all indexes on the table,
including the PRIMARY KEY.
• SHOW TABLE STATUS LIKE tablename\G − Reports details of the MySQL DBMS
performance and statistics.
Web Server vs Application Server
• What is Server?
• A server is a central repository where data and computer programs are
stored and accessed by the clients in the network.
• It helps you to manage network resources and provides shared services to
connect workstations.
• It also allows you to share data or hardware and software resources among
clients.
• There are mainly two types of servers
1) Webserver
2) Application server
What is a Web Server?
• The information is program logic, which takes the form of data and
method and not static HTML.
• The client allows you to employ the exposed business logic whenever
they want.
• For example, application servers, like the Apache Tomcat, power the
interactive parts of a website, which may appear depending on the
context of the request.
Differences Between Web Server vs Application
Server
Web Server Application Server
Web Server is a computer program or a computer that An application server is a sever type that helps you to host
runs the application. applications.
It is responsible for accepting HTTP requests from clients It exposes business logic to the clients, which generates
and serving back that HTTP responses. dynamic content.
The result is XML, JSON, and HTML, etc. files that contain
The result is a hypertext document storing the information
required data and can serve a special purpose depending upon
which is displayed to the user on a web browser.
the user’s needs.
The web server delivers static content. The application server delivers dynamic content.
Reduces longer-running processes that are resource-intensive. Reduces web traffic, which is not resource-intensive.
The web server supports HTTP Protocol. The application server supports HTTP and RPC/RMI protocols.
Web servers support scripting languages like PHP, Perl, JSP, Assist Application server services such as transaction support,
ASP, etc. connection pooling, object pooling.
Features of Web Server:
The code has to be compiled before it The code is usually executed without
can be executed compiling
• PHP means – Personal Home Page, but it now stands for the
recursive backronym PHP: Hypertext Preprocessor.
• PHP code may be embedded into HTML code, or it can be used in
combination with various web template systems, web content
management system and web frameworks.
PHP Syntax
•HTML is an added advantage when learning PHP Language. You can even learn PHP without knowing HTML
but it’s recommended you at least know the basics of HTML.
•Database management systems DBMS for database-powered applications.
•For more advanced topics such as interactive applications and web services, you will need JavaScript and
XML.
Why use PHP?
• Easy to Learn: It is easier to learn for anyone who has come across any programming language
for the first time.
• Free of Cost: Since it is an open-source language, therefore developers are allowed to use its
components and all methods for free.
• Flexible: Since It is a dynamically typed language, therefore there are no hard rules on how to
build features using it.
• Supports nearly all databases: It supports all the widely used databases, including MySQL,
ODBC, SQLite, etc.
• Secured: It has multiple security levels and provides us with a secure platform for developing
websites as it has multiple security levels.
• Huge Community Support: It is loved and used by a huge number of developers. The developers
share their knowledge with other people in the community that want to know about it.
Applications of PHP
• Server-side web development: It is a development where the program runs on a server dealing
with the generation of content of web page.
• Content management systems (CMS): It is a framework already designed by other programmers
and coders on which you can either contribute your knowledge and skills or just use those coders’
skills to design your own website or blog
• E-commerce websites: E-commerce, or electronic commerce, refers to the buying and selling of
goods and services over the Internet.
• Database-driven applications: It is a software application that relies on a database to store,
manage, and retrieve data. It utilizes a database management system (DBMS) to organize and
manipulate data, enabling efficient data storage, retrieval, and management.
• Web APIs: It is an API as the name suggests, it can be accessed over the web using the HTTP
protocol. It is a framework that helps you to create and develop HTTP-based RESTFUL services.
Advantages of PHP :
1.The most important advantage of PHP is that it’s open-source and free of cost. It
can be downloaded anywhere and is readily available to use for events or web
applications.
2.It is platform-independent. PHP-based applications can run on any OS like UNIX,
Linux, Windows, etc.
3.Applications can easily be loaded which are based on PHP and connected to the
database. It’s mainly used due to its faster rate of loading over slow internet speed
than other programming languages.
4.It has less learning curve because it is simple and straightforward to use. Someone
familiar with C programming can easily work on PHP.
5.It is more stable for a few years with the assistance of providing continuous
support to various versions.
Disadvantages of PHP :
1.It is not that secure due to its open-source, because the ASCII text file is often
easily available.
2.It is not suitable for giant content-based web applications.
3.It has a weak type, which can cause incorrect data and knowledge to users.
4.PHP frameworks got to learn to use PHP built-in functionalities to avoid writing
additional code.
5.Using more features of PHP framework and tools cause poor performance of
online applications.
6.PHP doesn’t allow change or modification in the core behavior of online
applications.
Data Types
• One must use the PHP standard tags, rather than the shorthand tags to delimit the PHP code.
Full tags :
<?PHP
PHP code
?>
Short tags:
<?
PHP code
?>
Strings
if ($x > 0)
{
echo "The number is positive";
}
else{
echo "The number is negative";
}
?>
if…elseif…else Statement: This allows us to use multiple if…else statements. We use this when there are
multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
else{
echo "Nothing to show";
}
?>
Switch Statement:
The “switch” performs in various cases i.e., it has various cases to
which it matches the condition and appropriately executes a particular
case block. It first evaluates an expression and then compares it with the
values of each case. If a case matches then the same case is executed. To
use the switch, we need to get familiar with two different keywords
namely, break and default.
1.The break statement is used to stop the automatic control flow into
the next cases and exit from the switch case.
2.The default statement contains the code that would execute if none of
the cases match.
• <?php
• # Here echo command is used to print
• echo "Hello, world!";
• ?>
<?php
$var1 =15;
$var2 = 30;
$sum = $var1 + $var2;
echo $sum, "\n";
$sum1 = $var1 + $var2;
echo $sum1;
?>
• <?php
• # Here echo command is used to print
• echo "Hello, world!";
• ?>
Output:
Hello, world!
• <?
• # Here echo command will only work if
• # setting is done as said before
• echo "Hello, world!";
• ?>
Regular Expressions
ABS DIV PI
ACOS EXP POW
ASIN FLOOR POWER
ATAN GREATEST RADIANS
ATAN2 LEAST RAND
AVG LN ROUND
CEIL LOG SIGN
CEILING LOG10 SIN
COS LOG2 SQRT
COT MAX SUM
COUNT MIN TAN
DEGREES MOD TRUNCATE
Date/Time Functions
ADDDATE EXTRACT SECOND
ADDTIME FROM_DAYS STR_TO_DATE
CURDATE HOUR SUBDATE
CURRENT_DATE LAST_DAY SUBTIME
CURRENT_TIME LOCALTIME SYSDATE
CURRENT_TIMESTAMP LOCALTIMESTAMP TIME
• Syntax
• $mysqli->query($sql,$resultmode)
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
• $mysqli->query($sql,$resultmode)
Sr.No. Parameter & Description
1 $sql
Required - SQL query to drop a MySQL database.
2 $resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT
depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
<html>
<head><title>Dropping MySQL Database</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
echo 'Connected successfully<br />';
$retval = mysqli_select_db( $conn, 'TUTORIALS' );
if(! $retval ) {
die('Could not select database: ' . mysqli_error($conn));
}
echo "Database TUTORIALS selected successfully\n";
mysqli_close($conn);
?>
</body>
</html>
Create MySQL Tables
• These arrays can store numbers, strings, and any object but
their index will be represented by numbers.
• By default array index starts from zero.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
• The associative arrays are very similar to numeric arrays in terms of functionality
but they are different in terms of their index.
• Associative array will have their index as a string so that you can establish a
strong association between key and values.
• To store the salaries of employees in an array, a numerically indexed array would
not be the best choice.
• Instead, we could use the employee’s names as the keys in our associative array,
and the value would be their respective salary.
• NOTE − Don't keep associative array inside double quote while printing
otherwise it would not return any value.
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(“a" => 2000, “b" => 1000, “c" => 500);
</body>
</html>
• Salary of a is 2000
• Salary of b is 1000
• Salary of c is 500
• Salary of a is high
• Salary of b is medium
• Salary of c is low
Multidimensional Arrays
• Description
• The MySQL SELECT statement is used to retrieve records from one or more
tables in MySQL.
SELECT [ ALL | DISTINCT | DISTINCTROW ]
[ HIGH_PRIORITY ]
[ STRAIGHT_JOIN ]
[ SQL_SMALL_RESULT | SQL_BIG_RESULT ] [ SQL_BUFFER_RESULT ]
[ SQL_CACHE | SQL_NO_CACHE ]
[ SQL_CALC_FOUND_ROWS ]
expressions
FROM tables
[WHERE conditions]
[GROUP BY expressions]
[HAVING condition]
[ORDER BY expression [ ASC | DESC ]]
[LIMIT [offset_value] number_rows | LIMIT number_rows OFFSET offset_value]
[PROCEDURE procedure_name]
[INTO [ OUTFILE 'file_name' options
| DUMPFILE 'file_name'
| @variable1, @variable2, ... @variable_n]
[FOR UPDATE | LOCK IN SHARE MODE];
Parameters or Arguments
ALL
Optional. Returns all matching rows
DISTINCT
Optional. Removes duplicates from the result set. Learn more about DISTINCT clause.
DISTINCTROW
Optional. Synonym for DISTINCT. Removes duplicates from the result set.
HIGH_PRIORITY
Optional. It tells MySQL to run the SELECT before any UPDATE statements that are waiting for the same
resource. It may be used with MyISAM, MEMORY and MERGE tables that use table-level locking.
STRAIGHT_JOIN
Optional. It tells MySQL to join the tables in the order that they are listed in the FROM clause.
SQL_SMALL_RESULT
Optional. Uses fast temporary tables to store results (used with DISTINCT and GROUP BY).
SQL_BIG_RESULT
Optional. Prefers sorting rather than using a temporary table to store results (used with DISTINCT and
GROUP BY).
SQL_BUFFER_RESULT
Optional. Uses temporary tables to store results (can not be used with subqueries).
SQL_CACHE
Optional. Stores the results in the query cache.
SQL_NO_CACHE
Optional. Does not store the results in the query cache.
SQL_CALC_FOUND_ROWS
Optional. Calculates how many records are in the result set (not taking into account the LIMIT modifier) which
can then be retrieved using the FOUND_ROWS function.
expressions
The columns or calculations that you wish to retrieve. Use * if you wish to select all columns.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
GROUP BY expressions
Optional. It collects data across multiple records and groups the results by one or more columns. Learn more about the
GROUP BY clause.
HAVING condition
Optional. It is used in combination with the GROUP BY to restrict the groups of returned rows to only those whose the
condition is TRUE. Learn more about the HAVING clause.
ORDER BY expression
Optional. It is used to sort the records in your result set. Learn more about the ORDER BY clause.
LIMIT
Optional. If LIMIT is provided, it controls the maximum number of records to retrieve. At most, the number of records
specified by number_rows will be returned in the result set. The first row returned by LIMIT will be determined by
offset_value.
PROCEDURE
Optional. If provided, procedure_name is the name of the procedure that should process the data in the result set.
INTO
Optional. If provided, it allows you to write the result set to either a file or variable.
Joins
Description
MySQL JOINS are used to retrieve data from multiple tables. A
MySQL JOIN is performed whenever two or more tables are joined in a
SQL statement.
There are different types of MySQL joins:
MySQL INNER JOIN (or sometimes called simple join)
MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
INNER JOIN (simple join)
Syntax
The syntax for the LEFT OUTER JOIN in MySQL is:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
RIGHT OUTER JOIN
Another type of join is called a MySQL RIGHT OUTER JOIN. This type of join
returns all rows from the RIGHT-hand table specified in the ON condition
and only those rows from the other table where the joined fields are equal (join
condition is met).
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
UNIT 5
Shell Scripting
Linux Kernel, Shell, Types of Shells, Shell scripting, Basic Shell scripts, If-then scripts, For loop scripts, Do-
while scripts, Case statement scripts, Aliases, Command history.
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.
•Command Line Shell
•Graphical shell
Command Line Shell
• 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.
• If you have any prior experience with any programming language like
Python, C/C++ etc. It would be very easy to get started with it.
• 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.
Why do we need shell scripts?
• The command and syntax are exactly the same as those directly
entered in the command line, so programmers do not need to switch to
entirely different syntax
• Writing shell scripts are much quicker
• Quick start
• Interactive debugging etc.
Some Disadvantages of shell scripts
•
Conditional statements
If statement
It checks the condition, and if it is conditioned true, it executes the
commands.
Syntax
if [ condition ]
then
#statements
fi
#!/bin/sh
x=10
y=11
if [ $x -ne $y ]
then
echo "Not equal"
fi
If-else statement
In an if-else statement, you can specify a set of commands to run if the condition is
not met.
Syntax
if [ condition ]
then
#set of statements if the condition is true
else
#set of statements if the condition is false
fi
#!/Syntaxbin/sh
x=10
y=10
if [ $x -ne $y ]
then
echo "Not equal"
else
echo "They are equal"
fi
Loops
In a for loop, the variable iterates over a list of values and ends when
there are no more values to iterate over.
Syntax
for var in val1 val2 val3
do
#statements
done
#!/bin/sh
for var in 2 4 5 8
do
echo $var
done
Positional Arguments
The code after the loop which was The code in the loop continues its
4
terminated is continued. execution skipping the current iteration.
Case statement scripts
• The bash case statement is the simplest form of the if elif else conditional
statement.
• The case statement simplifies complex conditions with multiple different choices.
• This statement is easier to maintain and more readable than nested if statements.
• The case statement tests the input value until it finds the corresponding pattern and
executes the command linked to that input value.
• Thus, it is an excellent choice for creating menus where users select an option
which triggers a corresponding action.
Bash case Statement Syntax
case $variable in
pattern-1)
commands;;
pattern-2)
commands;;
pattern-3)
commands;;
pattern-N)
commands;;
*)
commands;;
esac
The case statement starts with the case keyword followed by the $variable and the in keyword. The
statement ends with the case keyword backwards - esac.
$variable
The script compares the input $variable against the patterns in each clause until it finds a match.
Patterns
A pattern and its commands make a clause, which ends with ;;.
Patterns support special characters.
The ) operator terminates a pattern list.
The | operator separates multiple patterns.
The script executes the commands corresponding to the first pattern matching the input $variable.
The asterisk * symbol defines the default case, usually in the final pattern.
Exit Status
vi color.sh
The first line in each script is typically the shebang (#!), which instructs the operating system which interpreter to use
to parse the file.
Lines 2-7 are the options menu presented to the user to choose from.
The read color; variable prompts the user for an answer and stores it.
The case statement contains the possible responses that correspond to the user's input. In this example, the output is
the echo command output.
The last line, esac, ends the case statement.
Save the script and exit vi with the following command:
:wq
Before running each script, make sure to chmod it to make it executable:
chmod +x color.sh
./color.sh
#!/bin/bash
echo "Enter a character:"
read var
case $var in
[[:lower:]) echo "You entered a lowercase character.";;
[[:upper:]]) echo "You entered an uppercase character.";;
[0-9]) echo "You entered a digit.";;
?) echo "You entered a special character.";;
*) echo "You entered multiple characters.";;
Esac
hH6@