Understanding DevOps: Key Concepts & Benefits
Understanding DevOps: Key Concepts & Benefits
Every phase of the software development lifecycle, including planning, coding, testing,
deployment, and monitoring, is heavily automated in DevOps. This improves productivity,
ensures consistency, and lowers error rates in the development process. A culture of continuous
improvement is also promoted by DevOps, where feedback loops are incorporated into the
procedure to facilitate quicker iteration and better decision-making. Organizations can increase
their agility, lower costs, and speed up innovation by adopting DevOps.
Why DevOps?
The goal of DevOps is to increase an organization’s speed when it comes to delivering
applications and services. Many companies have successfully implemented DevOps to enhance
their user experience including Amazon, Netflix, etc.
Facebook’s mobile app which is updated every two weeks effectively tells users you can have
what you want and you can have it. Now ever wondered how Facebook was able to do social
smoothing? It’s the DevOps philosophy that helps Facebook ensure that apps aren’t outdated
and that users get the best experience on Facebook. Facebook accomplishes this true code
ownership model that makes its developers responsible that includes testing and supporting
through production and delivery for each kernel of code. They write and update their true
policies like this but Facebook has developed a DevOps culture and has successfully
accelerated its development lifecycle.
Industries have started to gear up for digital transformation by shifting their means to weeks and
months instead of years while maintaining high quality as a result. The solution to all this is-
DevOps.
How DevOps is different from Traditional IT?
Traditional IT has 1000s lines of code and is created by different teams with different standards
whereas DevOps is created by one team with intimate knowledge of the product. Traditional IT
is complex to understand and DevOps is easily understandable.
DevOps Lifecycle
DevOps lifecycle is the methodology where professional development teams come together to
bring products to market more efficiently and quickly. The structure of the DevOps lifecycle
consists of Plan, Code, Building, Test, Releasing, Deploying, Operating, and Monitoring.
Plan: Determining the commercial needs and gathering the opinions of end-user by
professionals in this level of the DevOps lifecycle.
Code: At this level, the code for the same is developed and in order to simplify the design, the
team of developers uses tools and extensions that take care of security problems.
Build: After the coding part, programmers use various tools for the submission of the code to
the common code source.
Test: This level is very important to assure software integrity. Various sorts of tests are done
such as user acceptability testing, safety testing, speed testing, and many more.
Release: At this level, everything is ready to be deployed in the operational environment.
Deploy: In this level, Infrastructure-as-Code assists in creating the operational infrastructure
and subsequently publishes the build using various DevOps lifecycle tools.
Operate: At this level, the available version is ready for users to use. Here, the department
looks after the server configuration and deployment.
Monitor: The observation is done at this level that depends on the data which is gathered from
consumer behavior, the efficiency of applications, and from various other sources.
Best Practices to follow:
Implement automated dashboard
Keep the entire team together
Allow DevOps to be a cultural change
Be patient with the developers
Maintain a centralized unit
Build a flexible infrastructure
Advantages:
Faster Delivery: DevOps enables organizations to release new products and updates faster and
more frequently, which can lead to a competitive advantage.
Improved Collaboration: DevOps promotes collaboration between development and operations
teams, resulting in better communication, increased efficiency, and reduced friction.
Improved Quality: DevOps emphasizes automated testing and continuous integration, which
helps to catch bugs early in the development process and improve the overall quality of
software.
Increased Automation: DevOps enables organizations to automate many manual processes,
freeing up time for more strategic work and reducing the risk of human error.
Better Scalability: DevOps enables organizations to quickly and efficiently scale their
infrastructure to meet changing demands, improving the ability to respond to business needs.
Increased Customer Satisfaction: DevOps helps organizations to deliver new features and
updates more quickly, which can result in increased customer satisfaction and loyalty.
Improved Security: DevOps promotes security best practices, such as continuous testing and
monitoring, which can help to reduce the risk of security breaches and improve the overall
security of an organization’s systems.
Better Resource Utilization: DevOps enables organizations to optimize their use of resources,
including hardware, software, and personnel, which can result in cost savings and improved
efficiency.
Disadvantages:
High Initial Investment: Implementing DevOps can be a complex and costly process, requiring
significant investment in technology, infrastructure, and personnel.
Skills Shortage: Finding qualified DevOps professionals can be a challenge, and organizations
may need to invest in training and development programs to build the necessary skills within
their teams.
Resistance to Change: Some employees may resist the cultural and organizational changes
required for successful DevOps adoption, which can result in resistance, resistance to
collaboration, and reduced efficiency.
Lack of Standardization: DevOps is still a relatively new field, and there is a lack of
standardization in terms of methodologies, tools, and processes. This can make it difficult for
organizations to determine the best approach for their specific needs.
Increased Complexity: DevOps can increase the complexity of software delivery, requiring
organizations to manage a larger number of moving parts and integrate multiple systems and
tools.
Dependency on Technology: DevOps relies heavily on technology, and organizations may need
to invest in a variety of tools and platforms to support the DevOps process.
Need for Continuous Improvement: DevOps requires ongoing improvement and adaptation, as
new technologies and best practices emerge. Organizations must be prepared to continuously
adapt and evolve their DevOps practices to remain competitive.
DevOps Lifecycle is the set of phases that includes DevOps for taking part in Development and
Operation group duties for quicker software program delivery. DevOps follows positive
techniques that consist of code, building, testing, releasing, deploying, operating, displaying,
and planning. DevOps lifecycle follows a range of phases such as non-stop development, non-
stop integration, non-stop testing, non-stop monitoring, and non-stop feedback. Each segment
of the DevOps lifecycle is related to some equipment and applied sciences to obtain the
process. Some of the frequently used tools are open source and are carried out primarily based
on commercial enterprise requirements. DevOps lifecycle is effortless to manipulate and it helps
satisfactory delivery.
7 Cs of DevOps
Continuous Development
Continuous Integration
Continuous Testing
Continuous Deployment/Continuous Delivery
Continuous Monitoring
Continuous Feedback
Continuous Operations
1. Continuous Development
In Continuous Development code is written in small, continuous bits rather than all at once,
Continuous Development is important in DevOps because this improves efficiency every time a
piece of code is created, it is tested, built, and deployed into production. Continuous
Development raises the standard of the code and streamlines the process of repairing flaws,
vulnerabilities, and defects. It facilitates developers’ ability to concentrate on creating high-
quality code.
2. Continuous Integration
Continuous Integration can be explained mainly in 4 stages in DevOps. They are as follows:
Getting the SourceCode from SCM
Building the code
Code quality review
Storing the build artifacts
The stages mentioned above are the flow of Continuous Integration and we can use any of the
tools that suit our requirement in each stage and of the most popular tools are GitHub for source
code management(SCM) when the developer develops the code on his local machine he
pushes it to the remote repository which is GitHub from here who is having the access can Pull,
clone and can make required changes to the code. From there by using Maven we can build
them into the required package (war, jar, ear) and can test the Junit [Link] performs
code quality reviews where it will measure the quality of source code and generates a report in
the form of HTML or PDF format. Nexus for storing the build artifacts will help us to store the
artifacts that are build by using Maven and this whole process is achieved by using a
Continuous Integration tool Jenkins.
3. Continuous Testing
Any firm can deploy continuous testing with the use of the agile and DevOps methodologies.
Depending on our needs, we can perform continuous testing using automation testing tools
such as Testsigma, Selenium, LambdaTest, etc. With these tools, we can test our code and
prevent problems and code smells, as well as test more quickly and intelligently. With the aid of
a continuous integration platform like Jenkins, the entire process can be automated, which is
another added benefit.
5. Continuous Monitoring
DevOps lifecycle is incomplete if there was no Continuous Monitoring. Continuous Monitoring
can be achieved with the help of Prometheus and Grafana we can continuously monitor and can
get notified before anything goes wrong with the help of Prometheus we can gather many
performance measures, including CPU and memory utilization, network traffic, application
response times, error rates, and others. Grafana makes it possible to visually represent and
keep track of data from time series, such as CPU and memory utilization.
6. Continuous Feedback
Once the application is released into the market the end users will use the application and they
will give us feedback about the performance of the application and any glitches affecting the
user experience after getting multiple feedback from the end users’ the DevOps team will
analyze the feedbacks given by end users and they will reach out to the developer team tries to
rectify the mistakes they are performed in that piece of code by this we can reduce the errors or
bugs that which we are currently developing and can produce much more effective results for
the end users also we reduce any unnecessary steps to deploy the application. Continuous
Feedback can increase the performance of the application and reduce bugs in the code making
it smooth for end users to use the application.
7. Continuous Operations
We will sustain the higher application uptime by implementing continuous operation, which will
assist us to cut down on the maintenance downtime that will negatively impact end users’
experiences. More output, lower manufacturing costs, and better quality control are benefits of
continuous operations.
Commands Description
Used to turn on or turn off the process for accounting or change info
accton process accounting file
acpi Used to display the battery status and other ACPI information
addr2line Used to convert addresses into file names and line numbers
Instructs the shell to replace one string with another string while
alias executing the commands
It helps the user when they don’t remember the exact command but
knows a few keywords related to the command that define its uses or
apropos functionality
ar Used to create, modify and extract the files from the archives
atd It is a job scheduler daemon that runs jobs scheduled for later execution
Used to remove the specified jobs. To remove a job, its job number is
atrm passed in the command
atq It displays the list of pending jobs which are scheduled by the user
Used for automatically generating [Link] files compliant with the set
automake GNU Coding Standards
Used to create automatically buildable source code for Unix-like
autoreconf systems
banner Used to print the ASCII character string in large letter to standard output
It strips directory information and suffixes from file names i.e. it prints the file
basename
name NAME with any leading directory components removed
Used to read commands from standard input or a specified file and execute
batch them when system load levels permit i.e. when the load average drops
below 1.5
A mail notification system for unix that notifies the user at the command line
biff
when new mail arrives and tells from whom it is
break Used to terminate the execution of for loop, while loop and until loop
Used to run a shell builtin, passing it arguments(args), and also to get the
builtin
exit status
bzcmp Used to invoke the cmp utility on bzip2 compressed files
It does not have to read the entire input file before starting, so with a large
bzless
file, it starts up faster
Used as a filter for CRT viewing of bzip2 compressed files, which are saved
bzmore
with .bz2 suffix
Reads data from file and gives their content as output. It helps us to create,
cat
view, concatenate files
chage Used to view and change the user password expiry information
It allows you to change a user’s name and other details easily. chfn stands
chfn
for Change finger
chkconfig Used to list all available services and view or update their run level settings
Used to compare the two files byte by byte and helps you to find out
cmp
whether the two files are identical or not
It is used to filter out reverse line feeds. The col utility simply reads from the
col
standard input and writes to standard output
Compares two sorted files line by line and write to standard output; the lines
comm
that are common and the lines that are unique
Used to reduce the file size. After compression, the file will be available with
compress
an added .Z extension
continue Used to skip the current iteration in for, while and until loop
cpio stands for “copy in, copy out“. It is used for processing the archive files
cpio
like *.cpio or *.tar. This command can copy files to and from archives
It is automatically used by C compiler to transform your program before
cpp
compilation
A list of commands that you want to run on a regular schedule, and also the
crontab
name of the command used to manage that list
csplit Used to split any file into many parts as required by the user
It allows quick access across the files (For example quickly seeing definition
ctags
of a function)
For cutting out the sections from each line of files and writing the result to
cut
standard output
Used to display the system date and time. It is also used to set date and
date
time of the system
Used to declare shell variables and functions, set their attributes and
declare
display their values
Used to display information related to file systems about total space and
df
available space
diff Used to display the differences in the files by comparing the files line by line
Used to remove the trailing forward slahes “/” from the NAME and prints the
dirname
remaining portion
Used to examine the kernel ring buffer and print the message buffer of
dmesg
kernel
dosfsck Diagnoses MS-DOS file system for problems and attempts to repair them
Used to track the files and directories which are consuming excessive
du
amount of space on hard disk drive
Used to print the super block and blocks group information for the
dumpe2fs
filesystem present on device
Used for launching the ed text editor which is a line-based text editor with a
ed minimal interface which makes it less complex for working on text files i.e
creating, editing, displaying and manipulating files
It treats the pattern as an extended regular expression and prints out the lines
egrep
that match the pattern
It is a text editor in Linux which is also termed as the line editor mode of the vi
ex
editor
Allows you to convert tabs into spaces in a file and when no file is specified it
expand
reads from standard input
This command or scripting language works with scripts that expect user inputs. It
expect
automates the task by providing inputs
It is bash shell BUILTINS commands, which means it is part of the shell. It marks
export
an environment variables to be exported to child-processes
Used to print the prime factors of the given numbers, either given from command
factor
line or read from standard input
Used to list, edit or re-execute the commands previously entered into an
fc
interactive shell
fc- It scans the font directories and build font cache for applications which use
cache fontconfig for their font handling
It is used to list the available fonts and font styles. Using the format option, the
fc-list
list of all fonts can be filtered and sorted out
find Used to find files and directories and perform subsequent operations on them
It is a user information lookup command which gives details of all the users
finger
logged in.
It wraps each line in an input file to fit a specified width and prints it to the
fold
standard output
Used to repeatedly execute a set of command for every element present in the
for
list
Displays the total amount of free space available along with the amount of
free memory used and swap memory in the system, and also the buffers used by the
kernel
GNU Debugger tool helps to debug the programs written in C, C++, Ada,
gdb
Fortran, etc.
getent Used to get the entries in a number of important text files called databases
Searches a file for a particular pattern of characters, and displays all lines
grep
that contain that pattern
It verifies the integrity of the groups information. It checks that all entries in
grpck
/etc/group and /etc/gshadow have the proper format and contain valid data
Used to instruct the hardware to stop all the CPU functions. Basically, it
halt
reboots or stops the system.
Used to get statistics about the hard disk, alter writing intervals, acoustic
hdparm
management, and DMA settings
Used to obtain the DNS(Domain Name System) name and set the system’s
hostname
hostname or NIS(Network Information System) domain name.
Provides a proper API used to control Linux system hostname and change
hostnamectl
its related settings
It is a command line utility that allows the user to interactively monitor the
htop
system’s vital resources or server’s processes in real time
hwclock Utility for accessing the hardware clock, also called Real Time Clock (RTC)
iconv Used to convert some text in one encoding into another encoding
Used to find out user and group names and numeric ID’s (UID or group ID) of
id
the current user or any other user in the server
Used for capturing a screenshot for any of the active pages we have and it
import
gives the output as an image file
Reads documentation in the info format. It will give detailed information for a
info
command when compared with the main page
iostat Used for monitoring system input/output statistics for devices and partitions
Used to display and monitor the disk IO usage details and even gets a table
iotop
of existing IO utilization by the process
Used to set up and maintain tables for the Netfilter firewall for IPv4, included
iptables
in the Linux kernel
iptables- It will save the current iptables rules in a user specified file, that can be used
save later when the user wants
Used to display the parameters, and the wireless statistics which are
iwconfig
extracted from /proc/net/wireless
It is a command line utility for joining lines of two files based on a key field
join
present in both the files
Used to display the list of all the users logged in and out since the file /var/log/wtmp
last
was created
less Used to read contents of text file one page(one screen) per time
Used to display details about block devices and these block devices(Except ram
lsblk
disk) are basically those files that represent devices connected to the pc.
Used to display the information about USB buses and the devices connected to
lsusb
them
This command in Linux prints the mail queue i.e the list of messages that are
mailq
there in the mail queue
Used to display the user manual of any command that we can run on the
man
terminal
Allows the user to create directories. This command can create multiple
mkdir
directories at once
Used to view the text files in the command prompt, displaying one screen at a
more
time in case the file is large (For example log files)
Used to move one or more files or directories from one place to another in file
mv
system like UNIX
It is one of the powerful networking tool, security tool or network monitoring
nc(netcat)
tool.
Used to convert the content of input in different formats with octal format as the
od
default format
pidof Used to find out the process IDs of a specific running program
ping Used to check the network connectivity between host and server/host
It is a user information lookup command which gives details of all the users
pinky logged in. Unlike finger, in the pinky, you may trim the information of your
interest.
Used to display the memory map of a process. A memory map indicates how
pmap
memory is spread out
poweroff Sends an ACPI signal which instructs the system to power down
Used to display the given string, number or any other format specifier on the
printf
terminal window
Used to list the currently running processes and their PIDs along with some
ps
other information depends on different options
pwd It prints the path of the working directory, starting from the root
Reads up the total number of bytes from the specified file descriptor into the
read
buffer
rename Used to rename the named files according to the regular expression perlexpr
Used to initialize the terminal. This is useful once a program dies leaving a
reset
terminal in an abnormal state
restore Used for restoring files from a backup created using dump
route Used when you want to work with the IP/kernel routing table
It is a software utility for Unix-Like systems that efficiently sync files and
rsync
directories between two hosts or machines
Provides the ability to launch and use multiple shell sessions from a single
screen
ssh session
select Used to create a numbered menu from which a user can select an option
prints to standard output either the scan codes or the key code or the `ascii’
showkey
code of each key pressed
sleep Used to create a dummy job. A dummy job helps in delaying the execution
sudo Used as a prefix of some command that only superuser are allowed to run
Used to examine and control the state of “systemd” system and service
systemctl
manager
Reads the standard input and writes it to both the standard output and one or
tee
more files
tracepath Used to traces path to destination discovering MTU along this path
traceroute Prints the route that a packet takes to reach the host
It displays the information related to terminal. It basically prints the file name of
tty
the terminal connected to standard input
type Used to describe how its argument would be translated if used as commands
Converts each spaces into tabs writing the produced output to the standard
unexpand
output
uniq It is a command line utility that reports or filters out the repeated lines in a file
Used to execute a set of commands as long as the final command in the ‘until’
until
Commands has an exit status which is not zero
Uptime Used to find out how long the system is active (running)
useradd Used to add user accounts to your system
usermod Used to change the properties of a user in Linux through the command line
users Used to show the user names of users currently logged in to the current host
It is the default editor that comes with the UNIX operating system is called visual
vi
editor.
Used to find out number of lines, word count, byte and characters count in the
wc
files specified in the file arguments
Used to download files from the server even when the user has not logged on to
Wget
the system and it can work in background without hindering the current process
Used to locate the executable file associated with the given command by
which
searching it in the path environment variable
whoami Displays the username of the current user when this command is invoked
Allows a user to communicate with other users, by copying lines from one user’s
write
terminal to others
Used to build and execute commands from standard input. It converts input
xargs
received from standard input into arguments of a command
xdg-
Used to open a file or URL in the user’s preferred application
open
zdiff Used to invoke the diff program on files compressed via gzip
Used to print the current time in the specified zone or you can say prints the
zdump
current time in each zonename named on the command line
zgrep Used to search out expressions from a given a file even if it is compressed
It is a compression and file packaging utility for Unix. Each file is stored in single
zip
.zip {.zip-filename} file with the extension .zip
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.
It is often mistaken that Linus Torvalds has developed Linux OS, but actually, he is only
responsible for the development of the Linux kernel.
Complete Linux system = Kernel + GNU system utilities and libraries + other management
scripts + installation scripts.
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.
Linux Shell
Shell is broadly classified into two categories –
Command Line Shell
Graphical shell
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 –
In the above screenshot “ls” command with “-l” option is executed. It will list all the files in the
current working directory in a long listing format.
Working with a command line shell is a bit difficult for beginners because it’s hard to memorize
so many commands. It is very powerful; it allows users to store commands in a file and execute
them together. This way any repetitive task can be easily automated. These files are usually
called batch files in Windows and Shell Scripts in Linux/macOS systems.
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. Window OS or Ubuntu OS can be
considered as a good example which provides GUI to the user for interacting with the program.
Users do not need to type in commands for every action. A typical GUI in the Ubuntu system –
There are several shells are available for Linux systems like –
BASH (Bourne Again SHell) – It is the most widely used shell in Linux systems. It is used
as default login shell in Linux systems and in macOS. It can also be installed on
Windows OS.
CSH (C SHell) – The C shell’s syntax and its usage are very similar to the C
programming language.
KSH (Korn SHell) – The Korn Shell was also the base for the POSIX Shell standard
specifications etc.
Each shell does the same job but understands different commands and provides different built-
in functions.
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.
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., [Link].
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?
There are many reasons to write shell scripts:
To avoid repetitive work and automation
System admins use shell scripting for routine backups.
System monitoring
Adding new functionality to the shell etc.
Some Advantages of 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
Prone to costly errors, a single mistake can change the command which might be
harmful.
Slow execution speed
Design flaws within the language syntax or implementation
Not well suited for large and complex task
Provide minimal data structure unlike other scripting languages. etc.
Simple demo of shell scripting using Bash Shell
If you work on a terminal, something you traverse deep down in directories. Then for coming
few directories up in path we have to execute a command like this as shown below to get to the
“python” directory:
# !/bin/bash
function jump()
{
# original value of Internal Field Separator
OLDIFS=$IFS
local pos=-1
For now, we cannot execute our shell script because it does not have permissions. We have to
make it executable by typing following command –
$ chmod +x path/to/our/file/[Link]
Now to make this available on every terminal session, we have to put this in “.bashrc” file.
“.bashrc” is a shell script that Bash shell runs whenever it is started interactively. The purpose
of a .bashrc file is to provide a place where you can set up variables, functions, and aliases,
define our prompt, and define other settings that we want to use whenever we open a new
terminal window.
Now open the terminal and type the following command:
$ echo “source ~/path/to/our/file/[Link]”>> ~/.bashrc
Now open your terminal and try out new “jump” functionality by typing following command-
$ jump dir_name
Basic Shell Commands in Linux
A shell is a special user program that provides an interface to the user to use operating system
services. Shell accepts human-readable commands from the user and converts them into
something which the kernel can understand. It is a command language interpreter that executes
commands read from input devices such as keyboards or from files. The shell gets started when
the user logs in or starts the terminal.
less: It is used to viewing the files instead of opening the [Link] to more command
but it allows backward as well as forward movement.
head : Used to print the first N lines of a file. It accepts N as input and the default value
of N is 10.
tail : Used to print the last N-1 lines of a file. It accepts N as input and the default value
of N is 10.
mv : Used to move the files or directories. This command’s working is almost similar
to cp command but it deletes a copy of the file or directory from the source path.
rm : Used to remove files or directories.
grep with Regular Expressions: Used to search for text using specific regular
expressions in file.
sort : This command is used to sort the contents of files.
Directories Description
It contains all the boot-related information files and folders such as conf, grub,
/boot etc.
/dev It is the location of the device files such as dev/sda1, dev/sda2, etc.
/mnt It contains temporary mount directories for mounting the file system.
It is a virtual file system for modern Linux distributions to store and allows
/sys modification of the devices connected to the system.
Configuration
Files Description
/etc/bashrc It is used by bash shell that contains system defaults and aliases.
/etc/inittab INIT process and their interaction at the various run levels.
/etc/profile.d It contains other scripts like application scripts, executed after login.
/etc/termcap An ASCII file that defines the behavior of different types of the terminal.
/etc/X11 Directory tree contains all the conf files for the X-window System.
To check the Linux directories, open the terminal and execute sudo -s followed by system
password to give root privilege. Then after changing the current home directory to the root
directory and check the list of all available directories in the base directory as shown below.
Input Output Redirection in Linux
In Linux, whenever an individual runs a command, it can take input, give output, or do both.
Redirection helps us redirect these input and output functionalities to the files or folders we
want, and we can use special commands or characters to do so.
For example, if we run the “date” command, it gives us output on the screen. However, if we
want to save the result in a file instead, we can use output redirection. This way, we can store
the output of the date command in a file and refer to it later. These redirections can come in
handy when we work with multiple and large outputs or inputs since we can use file data directly
as input and store results in files.
All this can be done easily on the terminal using some simple commands. In this article, we will
talk about different types of Redirections in linux and how to use Redirections in linux.
Types of Redirection
1. Overwrite Redirection:
Overwrite redirection is useful when you want to store/save the output of a command to a file
and replace all the existing content of that file. for example, if you run a command that gives a
report, and you want to save the report to the existing file of the previous report you can use
overwrite redirection to do this.
“>” standard output
“<” standard input
Implementation:
So whatever you will write after running this command, will be redirected and copied to the
“[Link]”. This is standard output redirection.
cat > [Link]
Now, this is standard input redirection, cat command will take the input from “[Link]” and print
it to the terminal screen. This line of code also shows the real working and meaning of the cat
command that is copy and paste. Many people have a misconception that the cat is used to
create a file, but it is not true, the main work of the cat is to copy the input and give the output to
the screen.
cat < [Link]
Just type cat on the terminal and hit enter. It will ask for the input lines, you could write your
name and hit enter. You will see your input will be reprinted.
(base) [root@localhost ~]# cat
Hello this is GeeksForGeeks
Hello this is GeeksForGeeks
This is used when we want to append some lines to the existing content of the file. If you use
only a single angular bracket all the content of the file will be lost.
cat >> [Link]
2. Append Redirection:
With the help of this Redirection, you can append the output to the file without compromising the
existing data of the file.
“>>” standard output
“<<” standard input
Implementation:
A here-document is used to redirect input into an interactive shell script or program. You can run
any program within a shell script without user action by supplying the required input for the
interactive program, or interactive shell script.
The general form for a here document is −
Syntax:
command << delimiter
document
delimiter
3. Merge Redirection:
This allows you to redirect the output of a command or a program to a specific file descriptor
instead of standard output. the syntax for using this is “>&” operator followed by the file
descriptor number.
“p >& q” Merges output from stream p with stream q
“p <& q” Merges input from stream p with stream q
Implementation:
Error Redirection: Error redirection is transferring the errors generated by some false
commands to a file rather than STDOUT.
Whenever a program is executed at the terminal, 3 files are generated: standard input(0),
standard output(1), standard error(2). These files are always created whenever a program is
run. By default, an error stream is displayed on the screen.
Examples:
1. In the below-mentioned example, the file descriptor used above is 2(STDERR). Using “2>” re-
directs the error output to a file named “[Link]” and nothing is displayed on STDOUT.
$ somerandomcommand 2>[Link]
2. Here, 2>&1 means that STDERR redirects to the target of STDOUT. More formally, the error
message generated by “2” gets merged with the current output “1“.
$ ls GEEK GFG > [Link] 2>&1
In the above example, the directory GEEK is not present. The error output is merged with the
standard output which in turn is being re-directed to “[Link]“.
Shell Scripting – Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer,
filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored
in memory. We have a few rules that have to be followed while writing variables in the script
(which will be discussed in the article). Overall knowing the shell variable scripting leads us to
write strong and good shell scripts.
Rules for variable definition
A variable name could contain any alphabet (a-z, A-Z), any digits (0-9), and an underscore ( _ ).
However, a variable name must start with an alphabet or underscore. It can never start with a
number. Following are some examples of valid and invalid variable names:
Valid Variable Names
ABC
_AV_3
AV232
Invalid variable names
2_AN
!ABD
$ABC
&QAID
Note: It must be noted that no other special character except underscore can be used in a
variable name because all other special characters have special meanings in Shell Scripting.
Defining Variables
Syntax
variable_name = <variable data>
Example
num="1"
name="Devil"
These kinds of variables are scalar variables as they could hold one value at a time.
1) Accessing variable
Variable data could be accessed by appending the variable name with ‘$’ as follows:
#!/bin/bash
VAR_1="Devil"
VAR_2="OWL"
echo "$VAR_1$VAR_2"
Output:
DevilOWL
Example of Accessing variable
2) Unsetting 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:
#!/bin/bash
var1="Devil"
var2=23
echo $var1 $var2
unset var1
# read-only variables
var_blood_group="O-"
readonly var_blood_group
echo "Blood group is $var_blood_group and read only."
echo "Error for read only variables, if trying to \
modify them."
echo
var_blood_group="B+"
echo
# unsetting variables
unset Var_age
echo "After unsetting var_age..."
echo
echo "Name is $Var_name, blood group is $var_blood_group\
and age is $Var_age..."
Output:
All outputs
Variable Types
We can discuss three main types of variables:
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.
Few more examples in Shell Scripting and Shell Variable
How to Store User Data in a Variable?
#!/bin/bash
echo "Enter the length of the rectangle"
read length
echo "Enter the width of the rectangle"
read width
area=$((length * width))
echo "The are of the rectangle is: $area"
In this example the variables ‘length’, ‘width’ and ‘area’ are used to store user input and
calculate the area of the rectangle.
Giving input to the variable
In this ‘echo’ is a command used to print the statement and ‘read’ is a command used to take
data from user and store it in a variable.
To Store and Display Message
We can write a script in which we will display a message to the user by looking at the time of the
day. In this we can use shell variable to store and display our message.
#!/bin/bash
time=$(date +%H)
if [ $time -lt 12];then
message = "Good Morning User"
elif [ $time -lt 18 ];then
message = "Good Afternoon User"
else
message = "Good Evening User"
fi
echo "$message"hours
if [ -e $filename ]
then
echo "$filename is exits on the directory"
cat $filename
else
cat > $filename
echo "File created"
fi
Output of Input & Output:
First time:
Enter filename
[Link]
Hello Geek
File created
Second time:
Enter filename
[Link]
[Link] is exits on the directory
Hello Geek
So, in this above example the first time, the script could not find any file with that file name, and
the else block gets executed. It created the file and put some data into that file. When we run it
a second time with the same file name, then it finds the file. So, is the if block gets executed and
that displays the contents of the file. Reading the file contents is input and on the first time
putting data into the file is considered to be output. Here we have used > for storing the content
in a file. The > notation is used to redirect stdout to a file. On the other hand, we can
use 2> notation to redirect stderr, and &> to redirect both stdout and stderr.
Below is the terminal shell pictorial depiction after executing the following script –
Functions
In programming, A function is a block of code that performs some tasks and it can be called
multiple times for performing tasks. The simplest example of the use of function in Bash
scripting can be given as –
Example Script:
#!/bin/bash
#It is a function
myFunction () {
echo Hello World from GeeksforGeeks
}
#function call
myFunction
Output of Functions:
Hello World from GeeksforGeeks
The above example shows a function that prints something when called.
So, the basic syntax for writing functions within a Bash Script will be –
Syntax of Functions:
#for defining
function_name(){
commands
.....
}
statements
fi
Example Script:
Name="Satyajit"
if [ "$Name" = "Satyajit" ]; then
echo "His name is Satyajit. It is true."
fi
Output of if-else statement:
His name is Satyajit. It is true.
In the above example, during the condition checking the name matches and the condition
becomes true. Hence, the block of code present within the if block gets executed. In case the
name doesn’t match then will not have an output. Below is the terminal shell pictorial depiction
after executing the following script –
2. case-sac statement:
case-sac is basically working the same as switch statement in programming. Sometimes if we
have to check multiple conditions, then it may get complicated using if statements. At those
moments we can use a case-sac statement. The syntax will be –
Syntax of case-sac statement:
case $var in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Example Script:
Name="Satyajit"
case "$Name" in
#case 1
"Rajib") echo "Profession : Software Engineer" ;;
#case 2
"Vikas") echo "Profession : Web Developer" ;;
#case 3
"Satyajit") echo "Profession : Technical Content Writer" ;;
esac
Output of case-sac statement:
Profession : Technical Content Writer
In the above example, the case-sac statement executed the statement which is a part of the
matched pattern here the ‘Name’. Below is the terminal shell pictorial depiction after executing
the following script –
Operator Description
Arithmetic operators are used for checking the arithmetic-based conditions. Like less than,
greater than, equals to, etc. Here is a descriptive table with all the operators –
Operator Description
-eq Equal
if [ 'Geeks' == 'Geeks' ];
then
echo "same" #output
else
echo "not same"
fi
Output of String and Numeric Comparisons:
Equal
same
In this example first one (-eq )is a numeric comparison that checks for equality. The second one
( == ) is also check for equality but in strings. Below is the terminal shell pictorial depiction after
executing the following script –
7. Unpack a package
–unpack flag helps us unpack the package.
dpkg --unpack [package-name]
dpkg --unpack flashplugin-nonfree_3.2_i386.deb
The output would look as shown below:
Note: In place of using domain name you can use IP address also. A ping operation can fail
if ping access is denied by a network firewall.
host
This command is used to obtain network address information about a remote system connected
to your network. This information usually consists of system’s IP address, domain name address
and sometimes mail server also.
Syntax:
$ host [Link]
finger
One can obtain information about the user on its network and the who command to see what
users are currently online on your system. The who command list all users currently connected,
along with when, how long, and where they logged in. finger can operate on large networks,
though most systems block it for security reasons.
Syntax:
$ finger [Link]
In place of ABC you can use any website domain or IP address.
traceroute
This command is used to track the sequence of computer networks. You can track to check the
route through which you are connected to a host. mtr or xmtr tools can also be used to perform
both ping and traces. Options are available for specifying parameters like the type of service (-t)
or the source host (-s).
netstat
This command is used to check the status of ports whether they are open, closed, waiting, and
masquerade connections. Network Statistic (netstat) command displays connection information,
routing table information, etc.
Syntax:
$ netstat
dig
dig(Domain Information Groper) query DNS-related information like a record, cname, mxrecord
etc. This command is used to solve DNS related queries.
Syntax:
$ dig [Link]
hostname
This command is used to see the hostname of your computer. You can change hostname
permanently in etc/sysconfig/network. After changing the hostname you need to reboot the
computer.
Syntax:
$ hostname
route
The route command is used to display or modify the routing table. To add a gateway use (-n).
Syntax:
$ route -n
nslookup
You can use nslookup(name server lookup) command to find out DNS related queries or testing
and troubleshoot DNS server.
Syntax:
$ nslookup [Link]
The ping command is used to ensure that a computer can communicate with a specified device
over the network. The pings command sends Internet Control Message Protocol (ICMP) Echo
Request messages in the form of packets to the destination computer and waits in order to get
the response back. Once the packets are received by the destined computer, it starts sending
the packets back. This command keeps executing until it is interrupted.
ping command provides details such as
the number of packets transmitted.
the number of packets received.
time is taken by the packet to return.
ping command is generally used for the following purposes:
measuring the time taken by the packets to return to determine the speed of the
connection.
to make sure that the network connection between the host and the destined computer
can be established.
ping [Link]
ping an IP
Using nslookup Command for Network configuration and troubleshooting
nslookup command queries the DNS in order to fetch the IP address or the domain name from
DNS records.
nslookup [Link]
Using traceroute Command for Network configuration and troubleshooting
This command is used to get the route of a packet. In other words, the traceroute command is
used to determine the path along which a packet travels. It also returns the number of hops
taken by the packet to reach the destination. This command prints to the console a list of hosts
through which the packet travels in order to the destination.
traceroute [Link]
Using host Command for Network configuration and troubleshooting
host command is used to find a domain name associated with the IP address or find an IP
address associated with the domain name. The returned IP address is either IPv4 or IPv6.
host [Link]
host [Link]
Using netstat Command for Network configuration and troubleshooting
netstat (Network Statistics) is the command that is used to display routing tables, connection
information, the status of ports, etc. This command works with Linux Network Subsystem. This
command basically displays the content of /proc/net file defined in the Linux file system.
netstat
netstat -r
Using Arp Command for Network configuration and troubleshooting
ARP (Address Resolution Protocol) command is used to display and modify ARP cache, which
contains the mapping of IP address to MAC address. The system’s TCP/IP stack uses ARP in
order to determine the MAC address associated with an IP address.
arp
arp -e
Using ifconfig Command for Network configuration and troubleshooting
ifconfig
Using Dig Command for Network configuration and troubleshooting
It is called domain information groper; it is a tool used to find query information related to
domain name and troubleshoot DNS issue in Linux. This tool can provide various types of DNS
records, such as CNAME, MX records and records etc.
For example: If we want to query a record for “[Link]”
syntax:
dig A [Link]
This will show the IP address associated with the domain name.
Using Route Command for Network configuration and troubleshooting
This tool helps us display and manipulate the routing table in Linux. Information contained by
this is about how network packets should be routed through a network.
Syntax:
route
This command shows destination, mask, flags, metric, gateway, reference count, and interface.
We can also add or delete routes from a network with IP address.
For example: If we have “IP address: [Link]” and “Subnet mask = 24” and “gateway
(gw) = [Link]”
syntax:
route add -net [Link]/24 gw [Link]
Using Ethtool Command for Network configuration and troubleshooting
This tool is used to view and modify the settings of a network interface card (NIC) in Linux. It
has replaced the old tool named mii-tool. This command can be used to view the current speed
and duplex setting of the NIC. To view the settings for the NIC named “enp0s3” use the
following command.
Syntax:
enthool enp0s3
You can find your NIC name by using “ifconfig” command.
Ethtool
Using Hostname Command for Network configuration and troubleshooting
This command is used to display the current hostname of the system.
Hostname
We can also change our host name by using commands.
syntax:
hostnamectl set-hostname mypc
This will set the hostname to “mypc” and display it after reboot also.
Linux SSH Server (sshd) Configuration and Security Options With Examples
SSH is short for Secure Shell or Secure Socket shell. According to Wikipedia, the Secure Shell
Protocol is a cryptographic network protocol for operating network services securely over an
unsecured network. sshd is short for Secure shell daemon. SSH is one of the most reliable
ways that you can choose to secure your Linux server-Virtual Private Server, which may be
hosted on the Cloud or a server that you have hosted locally on your machine.
This article assumes that you already have ssh utilities installed on your Linux machine.
Configuration and Security Options
Step 1: Generate ssh key pairs using the keygen utility.
Open your Linux terminal and connect to your server. Next on the client side(open another
terminal) run the following commands to log in using ssh key pairs. To generate public and
private key pairs execute the below command:
ssh-keygen -t rsa -b 2048 -C “put any comments here”
To view, the id_rsa.pub key, then run execute the below command.
cat .ssh/id_rsa.pub
Remove the “#” symbol before the PasswordAuthentication (or any option that you wish to
modify) and change it to no. Make sure that the PubkeyAuthentication is set to yes The
authorized keys file shows all the keys that you have generated.
Now restart the ssh service by running the below command:
systemctl restart ssh
When you open the sshd configuration, you will notice many options there. We will discuss
some of them here.
Option 1: Port 22
The port by default is set to 22. If you wish to change the default settings, remove the comments
and enter a port of your choice. It is recommended that you do not use port 22 as anyone trying
the infiltrate your system is most likely to check port 22 for vulnerabilities first.
Option 4: MaxSessions
This option allows you to enter a limit on the number of sessions that a user can have active.
Just in case the user ever leaks their passwords, this option provides additional security.
Max Auth Tries and Max Sessions- changing the defaults
Option 5: Choosing your desired algorithm
The default algorithm for public and private keys is the RSA algorithm. However, you can
change the type of the algorithm to suit your needs using the following key generation
command:
ssh-keygen -t {put the name of your desired algorithm over here} -b 2048 -C “put any comments
here”
Linux Virtualization : Linux Containers (lxc)
Operating-system-level virtualization is a server virtualization method in which an operating
system’s kernel allows multiple isolated user-space instances, instead of just one. Such
instances, which are sometimes called containers, software containers, virtualization engines
(VEs), or jails (FreeBSD jail or chroot jail), may look and feel like a real server from the point of
view of its owners and users.
The above definition sums up the broad idea about containers, but to be more accurate, the
traditional Virtual Machines used a hypervisor that runs on top of a kernel. This hypervisor
provides virtualization to the applications that run on it by monitoring their resource usage and
access patterns. This causes a lot of overhead resulting in unnecessary loss of performance.
On the other hand, Operating-system-level virtualization works differently. It uses namespaces
and cgroups to restrict the application’s capabilities including the use of resources. This is a
feature provided by the Linux kernel. This has almost no overhead.
cgroups
This method is so effective that Docker is using these containers internally to provide that
isolated environment which is very useful for deploying multiple integrated systems. They are
even bound towards creating their own containers library. Google have their own services
running on containers on shared hardware.
Install `lxc` in Linux Operating System
To install lxc in Ubuntu,
$ sudo apt-get install lxc lxctl lxc-templates
This package installs LXC’s requirements, some templates and also sets up the network
structure for the containers.
Run `lxc-checkconfig` to check if the kernel configuration is ready.
$ sudo lxc-checkconfig
Kernel configuration not found at /proc/[Link]; searching...
Kernel configuration found at /boot/config-4.4.0-24-generic
--- Namespaces ---
Namespaces: enabled
Utsname namespace: enabled
Ipc namespace: enabled
Pid namespace: enabled
User namespace: enabled
Network namespace: enabled
Multiple /dev/pts instances: enabled
Note: Before booting a new kernel, you can check its configuration usage:
“CONFIG=/path/to/config /usr/bin/lxc-checkconfig”
You should also see the output something similar to the above.
lxc provides a lot of ready templates, which are really helpful for fast deployment.
$ ls -l /usr/share/lxc/templates/
total 404
-rwxr-xr-x 1 root root 12973 May 18 14:48 lxc-alpine
-rwxr-xr-x 1 root root 13713 May 18 14:48 lxc-altlinux
-rwxr-xr-x 1 root root 11090 May 18 14:48 lxc-archlinux
-rwxr-xr-x 1 root root 12159 May 18 14:48 lxc-busybox
-rwxr-xr-x 1 root root 29503 May 18 14:48 lxc-centos
-rwxr-xr-x 1 root root 10374 May 18 14:48 lxc-cirros
-rwxr-xr-x 1 root root 19732 May 18 14:48 lxc-debian
-rwxr-xr-x 1 root root 17890 May 18 14:48 lxc-download
-rwxr-xr-x 1 root root 49600 May 18 14:48 lxc-fedora
-rwxr-xr-x 1 root root 28384 May 18 14:48 lxc-gentoo
-rwxr-xr-x 1 root root 13868 May 18 14:48 lxc-openmandriva
-rwxr-xr-x 1 root root 15932 May 18 14:48 lxc-opensuse
-rwxr-xr-x 1 root root 41720 May 18 14:48 lxc-oracle
-rwxr-xr-x 1 root root 11205 May 18 14:48 lxc-plamo
-rwxr-xr-x 1 root root 19250 May 18 14:48 lxc-slackware
-rwxr-xr-x 1 root root 26862 May 18 14:48 lxc-sparclinux
-rwxr-xr-x 1 root root 6862 May 18 14:48 lxc-sshd
-rwxr-xr-x 1 root root 25602 May 18 14:48 lxc-ubuntu
-rwxr-xr-x 1 root root 11439 May 18 14:48 lxc-ubuntu-cloud
We’ll start by creating a new container with the name “my_container” with “ubuntu”
template.
This will take some time and finish creating a container for you. Yes! It’s that simple.
Once it’s completed, the last few lines show the password for the root user of the
container. It would look something similar to this,
$ sudo lxc-create -n my_container -t ubuntu
.....
.....
##
# The default user is 'ubuntu' with password 'ubuntu'!
# Use the 'sudo' command to run tasks as root in the container.
##
We can check the status of container using lxc-ls. This will show the container to be in a
stopped state.
$ sudo lxc-ls --fancy
NAME STATE IPV4 IPV6 AUTOSTART
----------------------------------------------
my_container STOPPED - - NO
Now to start the container run lxc-start. The -d argument creates a daemon.
$ sudo lxc-start -n my_container -d
Check the status of container using lxc-ls to verify its running. We can access the console using
lxc-console. Use the credentials we received above to get the console access.
$ sudo lxc-console -n my_container
After logging in, run the following command on the container,
$ top
And on the host-pc run the following command to see the list of running processes.
$ ps auxf
and somewhere you’ll find a process tree that looks similar to this,
It would be surprising, but all the processes on the container are just simple processes on the
host pc. The important part is that all are isolated and monitored by kernel. Hence you can think
of these as simple processes on the host PC and you can even kill them (only if you have
sufficient privileges)
You can exit the console and return to the host by typing Ctrl-A followed by Q.
You can access the root filesystem of this container directly from the host machine by
accessing. You will need root permission to do so.
$ sudo su
$ cd /var/lib/lxc/my_container/rootfs
That’s it. Now this is like a brand-new operating system. You can run any service on this
container.
Think of containers as separate operating systems, where you can run anything, you want. The
only thing that makes it special is that all containers run on the same hardware. So, practically,
companies/institutions buy a heavy shared machine then deploy containers with resource limits
according to the multiple services they want. This makes it scalable and easier to manage.
This process takes a while because there are a lot of packages to be collected and the creation
of a container is also time taking.
Step 2: Listing the container(s)
Use the below command to list the available containers on your system:
sudo lxc-ls
By default the user created is ubuntu and the password is also ubuntu.
To see the complete details about the container use the below command:
sudo lxc-info -n <name_of_container>
Verify it:
sudo lxc-info -n <name_of_container>
Step 5: Freezing and Unfreezing
With the help of the lxc-freeze command we can freeze the containers:
sudo lxc-freeze -n <name_of_container>
The clone of the container can also be seen along with the existing container.
Step 7: Powering off the container
To power off the container use the below command:
sudo poweroff
Verify it once the container is stopped: