Shell
Shell
Linux Introduction:
Linux is Open Source Operating system developed by a Finnish student LinuS Torvalds in 1991.
Linux is compatible on many h/w like Macs, Mainframes, super computers, cell phones etc.
Operating system is the software which acts as the interface between the hardware and the
software we want to run on the hardware
Laptop/desktop is hardware
Ex:
Mobile is hardware
Symbiosis
Ios
android is OS
Linux Architecture
Linux has
Kernel Heart of OS, talks to H/w, provides low level services to upper layer components
Shell is the screen that user use to interact with operating system
LUI – Line User interface – looks like DOS (Disk Operating system )prompt
ROOT:
Capitazalation:
Windows is case insensitive, 2 files cannot be created wth names File, file.
Linux is case sensitive, 2 files can be created with names File, file
Server vs Desktop:
Server version is stripped down version of Linux – no GUI, lot of other tools are not installed
automatically, it has what a server needs.
Desktop version: gives GUI version of Linux – looks like Windows/Mac.
Every distro has desktop and server editions ex: readhat/Ubuntu etc
Linux Distributions:
People started developing their own code out of kernel developed by Linus
Example:
Redhat
Ubuntu
Google android
Fedora
Centos
Open source:
All open source software is not free (usage is free, support is not free)
They will give free software, but support they will charge
BIOS – Basic Input Output System – does POST Poweron Self Test – checks whether all i/o
devices are working fine (mouse monitor keyboard RAM HDD etc ), searches loads and executes
boot loader program
it has 3 components
The Master Boot Record (MBR) is the information in the first sector of any hard disk or diskette
that identifies how and where an operating system is located so that it can be boot (loaded)
into the computer's main storage or random access memory.
The Master Boot Record is also sometimes called the "partition sector" or the "master partition
table" because it includes a table that locates each partition that the hard disk has been
formatted into. In addition to this table, the MBR also includes a program that reads the boot
sector record of the partition containing the operating system to be booted into RAM. In turn,
that record contains a program that loads the rest of the operating system into RAM.
GRUB – Grand Unified Boot loader - responsible for selecting OS, loads kernel into memory
if multiple OS images are present, one image can be chooses using GRUB
GRUB displays a splash screen, waits for sometime, if user does not choose anything, it loads
default kernel
Kernel –
PID 1
init
Runlevel programs
0 – halt
4 – unused
6 – reboot
Run levels:
Under the /etc/rc.d/rc*.d/ directories, you would see programs that start with S and K.
There are numbers right next to S and K in the program names. Those are the sequence number
in which the programs should be started or killed.
Linux Installation
Linux can be installed using CD/USD/using iso image/using network installation like kickstart
Or single machine can be installed using iso (which can be downloaded from net)
example:
redhat-7.3-x86_64.ga.iso
Directory structure:
/root
/tmp
/bin/
/lib
/usr
/var
/etc
/home
/boot
/opt
iso;
ctx1p25 – shortname
ctx1p25.in.xyz.com – FQDN
Basic Commands
ls; ls –lrt
root@ctx2p02:~# ls -lrt
total 44
root@ctx2p02:~#
cd changes directory
mkdir , mkdir –p
mkdir → create directory
rm , rm –rf
rm → remove a directory
umask → decides the default permissions with which a file/directory will be created by a user.
cp, cp –r
cp → copies a file
syntax:
scp [email protected]:/tmp/file .
mount
syntax:
mounts file system from /mount from 192.168.100.101 to local machine in the mount point
/mnt
umask to decide the default permissions with which a file/directory will be created by a user.
Default
Umask 022
For a directory:
> this operator creates a new file , overwrites if any file exists
>> this operator creates a new file, appends to file, if the file exists
Editors:
vi vim editor
insert mode – press i to go to insert mode
yy to copy a line
p to paste
dd to cut
:w → save file
:q quit
split files
Editors usage:
Nano is for normal users. Emacs and Vim are for programmers
Vim/emacs – shows the loops /functions in different colour forms, easy to understand
syntax
grep
awk
sed
root 022
nohup
less
more
sed - stream editor
awk
redhat:
rpm –e → to remove
Ubuntu
dpkg
dpkg –I → to install
dpkg –r → to remove
for redhat/centos/fedora
yum
to configure:
/etc/yum.repos.d/iso.repo → to install from iso
AIX commands:
installp → to install
grep command:
grep -q
grep -A3
egrep '|'
fgrep old
egrep
extended grep
grep uses basic regular expressions where the plus is treated literally, any line with a plus in it is
returned.
fgrep
fixed grep
Then only the lines that have a literal '.' in them are returned. fgrep helps us not bother
escaping our meta characters.
? one
* 0 or more
[]
telnet
ssh
ping
traceroute
nslookup
tar
untar
zip
yum
yast
apt-get
rpm
dpkg
top
pstree
vmstat
sar
iostat
stat
cpio
dd
fdisk –l
lsblk
partitions – primary
extended
DNS
LDAP
reverse DNS
find
find . –name xx
find . – mtime 5
LVM – creating
RAIDs
software raid
hardware raid
Ubuntu – apt-get
SLES – yast
1) using iso
2) Using internet
Using iso:
2) update /etc/yum.repos.d/iso.repo
[iso]
name=iso
baseurl=file:/mnt/
enabled=1
gpgcheck=0
that instructs the shell to execute this script using the interpreter
$# - no. of args
$@ - all args
$* - all args
$0 – file name
$1 – first argument
$n – nth arg
$$ - PID
echo – to print
sh –vx to debug
1.cleanup script
# Cleanup
cd /var/log
#!/bin/bash
# Cleanup, version 2
# Insert code here to print error message and exit if not root.
LOG_DIR=/var/log
cd $LOG_DIR
[1] at the head of a script tells your system that this file is a set of commands to be fed
to the command interpreter indicated. The #! is actually a two-byte
[2] magic number, a special marker that designates a file type, or in this case an
executable shell script (type man magic for more details on this fascinating topic).
Immediately following the sha-bang is a path name. This is the path to the program that
interprets the commands in the script, whether it be a shell, a programming language,
or a utility. This command interpreter then executes the commands in the script,
starting at the top (the line following the sha-bang line), and ignoring comments. [3]
#!/bin/sh
#!/bin/bash
#!/usr/bin/perl
#!/usr/bin/tcl
#!/bin/sed -f
#!/bin/awk -f
Each of the above script header lines calls a different command interpreter
More commonly seen in the literature as she-bang or sh-bang. This derives from the
concatenation of the tokens sharp (#) and bang (!)
Case statement:
case "$variable" in
abc) echo "\$variable = abc" ;;
xyz) echo "\$variable = xyz" ;;
esac
#!/bin/bash
STR="Hello World!"
echo $STR
for i in "$@"
do
echo $i # loop $# times
done
for i in "$*"
do
done
It's safer to use "$@" instead of $*. When you use multiword strings as arguments to a
shell script, it's only "$@" that interprets each quoted argument as a separate
argument.
As the output above suggests, if you use $*, the shell makes a wrong count of the
arguments.
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
echo $5
echo $6
echo $7
echo $8
echo $9
#!/bin/bash
#read a;
#read b;
#sum=0;
a=$1;
b=$2;
sum=`expr $a + $b`;
echo $sum;
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
echo $5
echo $6
echo $7
echo $8
echo $9
echo $10
echo $11
echo $12
echo $13
echo $14
filename ./2.sh
10
11
12
13
#!/bin/bash
echo $1
echo $2
echo $3
shift;
echo $1
echo $2
echo $3
filename ./2.sh
Bfore shift
After shift
3
[root@r8r3m2kvm tmp]#
#!/bin/bash
read n;
read m;
l=`expr $n + $m`;
enter a variable
enter a variable
The sum is 3
[root@r8r3m2kvm tmp]#
Define a variable using
var=10
vehicle=bus
Rules:
a=10 right
echo $ var
Pipes
filters
bc-linux calculator
#!/bin/bash
#program to showif
echo “entera”
read a
echo “enterb”
read b
if [ a==b]
then
else
fi
if [ test $1 –gt 0 ]
then
fi
if conditions:
-s file- empty
-f file exists
-d directory – r read
-w write
-x execute
if [ ]
then
do this
fi
if []
then
dothis
else
dothis
fi
if []
then
dothis
elif []
then
do this
else
dothis
fi
if []
then
dothis
else
if []
then
fi
fi
fi
1)
if [ -f file ]
then
fi
if[ -f file ]
then
echo “fileexists”
else
echo”filedoes notexists”;
fi
$n=100
then
echo “n is 100 “;
then
echo “nisgtthatn100”;
else
echo”countislessthan 100”;
fi
test-
#!/usr/bin/bash
read filename
if [ -f $filename ]
then
else
touch $filename;
if [ $? -eq 0 ]
then
else
fi
fi
#!/usr/bin/bash
read a;
read b
if (( $a >= $b ))
then
else
fi
#!/usr/bin/bash
# while loop
i=100;
while (( $i >= 0 ))
do
echo $i;
i=`expr $i - 1`;
done
[root@rscthydnet1 ~]#
#!/usr/bin/bash
read a;
read b
if [ "$a" == "$b" ]
then
echo "equal"
else
fi
operators
-eq equal to
#!/usr/bin/bash
i=100;
while [ $i -ge 0 ]
do
echo $i;
i=`expr $i - 1`;
done
#!/usr/bin/bash
i=0;
while [ $i -le 10 ]
do
echo $i;
i=`expr $i + 1`;
done
For loop:
Below script prints 1 2 3 4 5 on the screen
#!/usr/bin/bash
for i in 1 2 3 4 5
do
echo $i
done
#!/usr/bin/bash
do
do
echo -n $i;
done
done
000000
111111
222222
333333
444444
555555
Case statement:
#!/usr/bin/bash
read n;
case $n in
esac
[root@r8r3m2kvm ~]#
#!/usr/bin/bash
echo "Enter 1 for bus, 2 for car, 3 for bike, 4 for van";
read n;
case $n in
*) echo "you have entered something else, please choose the right option";;
esac
Fibonacci series:
#!/bin/bash
read n
x=0
y=1
i=2
echo "$x"
echo "$y"
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done
~
#!/bin/bash
read n
x=0
y=1
i=2
echo "$x"
echo "$y"
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done
Functions:
Saves lot of time.
#!/usr/bin/bash
sayhello()
sayhello;
[root@r8r3m2kvm ~]#
[root@r8r3m2kvm ~]# cat fun.sh
#!/usr/bin/bash
sayhello()
sayhello;
declaration /definition
calling function
#!/usr/bin/bash
generate_list ()
{
echo "one two three"
do
echo "$word"
done
root@ctx2p02:~# ./1.sh
Hello abc
Hi
#!/bin/bash
sayhello()
sayhi;
return 100;
sayhi()
echo "Hi";
}
sayhello abc;
root@ctx2p02:~# . 1.sh
Hello abc
Hi
root@ctx2p02:~# sayhello
Hello
Hi
root@ctx2p02:~# sayhi
Hi
factorial of a number:
factorial()
then
i=`expr $1 - 1`;
j=`factorial $i`;
k=`expr $1 \* $j`;
echo $k;
else
echo 1
fi
read x;
factorial $x;
getopts:
to take inputs from command line
example:
#!/bin/bash
# Usage: ani -n -a -s -w -d
#
#
# help_ani() To print help
#
help_ani()
{
echo "Usage: $0 -n -a -s -w -d"
echo "Options: These are optional argument"
echo " -n name of animal"
echo " -a age of animal"
echo " -s sex of animal "
echo " -w weight of animal"
echo " -d demo values (if any of the above options are used "
echo " their values are not taken)"
exit 1
}
#
isdef=0
na=Moti
age="2 Months"
sex=Male
weight=3Kg
#
#if no argument
#
if [ $# -lt 1 ]; then
help_ani
fi
while getopts n:a:s:w:d opt
do
case "$opt" in
n) na="$OPTARG";;
a) age="$OPTARG";;
s) sex="$OPTARG";;
w) weight="$OPTARG";;
d) isdef=1;;
\?) help_ani;;
esac
done
if [ $isdef -eq 0 ]
then
echo "Animal Name: $na, Age: $age, Sex: $sex, Weight: $weight (user
define mode)"
else
na="Pluto Dog"
age=3
sex=Male
weight=20kg
echo "Animal Name: $na, Age: $age, Sex: $sex, Weight: $weight (demo
mode)"
fi
Regular expressions:
^ –Caret/Power symbol to match a starting at the beginning of line.
? – matches one or no chanracters (The preceding item is optional and will be matched,
at most, once.)
[] –Range of character
–Escape character
root@ctx2p02:/var/tmp# ls -l | grep ^d
root@ctx2p02:/var/tmp#
#!/bin/bash
root@ctx2p02:/var/tmp#
1.sh:
1.sh:
2.sh:
2.sh:
2.sh:
2.sh:
2.sh:
3.sh:
3.sh:
3.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
8.sh:
fact.sh:
fact.sh:
fact.sh:
file:
grep: systemd-private-56136dd90e4f4901bdc3fa6db5ac108b-systemd-
timesyncd.service-dxHQKZ: Is a directory
grep: systemd-private-df9fa18523f14518a8244c0bacba7692-systemd-
timesyncd.service-ENs3ex: Is a directory
root@ctx2p02:/var/tmp#
root@ctx2p02:/var/tmp#
aa
aaa
fact.sh
fib.sh
systemd-private-56136dd90e4f4901bdc3fa6db5ac108b-systemd-timesyncd.service-
dxHQKZ
systemd-private-df9fa18523f14518a8244c0bacba7692-systemd-timesyncd.service-
ENs3ex
root@ctx2p02:/var/tmp#
total 0
[root@reviewb abc]#
10.sh
1.sh
2.sh
3.sh
7.sh
8.sh
9.sh
fact.sh
fib.sh
file
file90
systemd-private-56136dd90e4f4901bdc3fa6db5ac108b-systemd-timesyncd.service-
dxHQKZ
systemd-private-df9fa18523f14518a8244c0bacba7692-systemd-timesyncd.service-
ENs3ex
until.sh
root@ctx2p02:/var/tmp#
root@ctx2p02:/var/tmp# grep '\[' *
2.sh:if [ $? -eq 0 ]
7.sh:while [ $k -lt $n ]
grep: systemd-private-56136dd90e4f4901bdc3fa6db5ac108b-systemd-
timesyncd.service-dxHQKZ: Is a directory
grep: systemd-private-df9fa18523f14518a8244c0bacba7692-systemd-
timesyncd.service-ENs3ex: Is a directory
until.sh:until [ $a -lt 10 ]
root@ctx2p02:/var/tmp#
total 56
root@ctx2p02:/var/tmp#
root@ctx2p02:/var/tmp#
total 56
root@ctx2p02:/var/tmp#
AWK
3.sh
fib.sh
1.sh
2.sh
7.sh
fact.sh
8.sh
10.sh
until.sh
file90
9.sh
a
file
aa
aaa
root@ctx2p02:/var/tmp#
19:42 systemd-private-56136dd90e4f4901bdc3fa6db5ac108b-systemd-
timesyncd.service-dxHQKZ
11:15 systemd-private-df9fa18523f14518a8244c0bacba7692-systemd-
timesyncd.service-ENs3ex
06:31 3.sh
07:07 fib.sh
07:19 1.sh
09:21 2.sh
20:45 7.sh
21:58 fact.sh
21:59 8.sh
05:49 10.sh
08:42 until.sh
09:14 file90
05:21 9.sh
05:24 a
05:27 file
05:28 aa
05:29 aaa
root@ctx2p02:/var/tmp#
root@ctx2p02:/var/tmp# ls -lrt | awk '{print $8 "," $9}'
19:42,systemd-private-56136dd90e4f4901bdc3fa6db5ac108b-systemd-
timesyncd.service-dxHQKZ
11:15,systemd-private-df9fa18523f14518a8244c0bacba7692-systemd-
timesyncd.service-ENs3ex
06:31,3.sh
07:07,fib.sh
07:19,1.sh
09:21,2.sh
20:45,7.sh
21:58,fact.sh
21:59,8.sh
05:49,10.sh
08:42,until.sh
09:14,file90
05:21,9.sh
05:24,a
05:27,file
05:28,aa
05:29,aaa
root@ctx2p02:/var/tmp#
total 56
drwx------ 3 root root 4096 Oct 7 19:42 systemd-private-
56136dd90e4f4901bdc3fa6db5ac108b-systemd-timesyncd.service-dxHQKZ
root@ctx2p02:/var/tmp#
Count = 8
root@ctx2p02:/var/tmp#
7.sh
root@ctx2p02:/var/tmp#root@ctx2p02:/var/tmp#
7.sh
root@ctx2p02:/var/tmp#
Syntax:
BEGIN { …. initialization awk commands …}
10693
root@ctx2p02:/var/tmp#
SED
By default, the sed command replaces the first occurrence of the pattern in each line and it
won't replace the second, third...occurrence in the line.
sed 's/unix/linux/3g' file.txt - The following sed command replaces the third, fourth, fifth...
"unix" word with "linux" word in a line.
There might be cases where you want to search for the pattern and replace that pattern by
adding some extra characters to it. In such cases & comes in handy. The & represents the
matched string.
sed 's/unix/{&}/' file.txt
{unix} {unix}
linux
{unix}
root@ctx2p02:/var/tmp#
The /p print flag prints the replaced line twice on the terminal. If a line does not have the
search pattern and is not replaced, then the /p prints that line only once.
linux unix
linux unix
linux
linux
linux
unix unix
linux
unix
xyz
XYZ
abc
ABC
Def
xyz
XYZ
abc
ABC
def
You can restrict the sed command to replace the string on a specific line number. An
example is
unix unix
linux
linux
linux unix
linux
linux
root@ctx2p02:/var/tmp#
unix unix
linux
linux
Here $ indicates the last line in the file. So the sed command replaces the text from
second line to last line in the file.
Here the sed command looks for the pattern "unix" in each line of a file and prints those
lines that has the pattern.
You can also make the sed command to work as grep -v, just by using the reversing the
sed with NOT (!).
after:
unix unix
linux
unix
before :
unix unix
linux
"Add a new line"
unix
it can be used to replace an entire line with a new line. The "c" command to sed tells it
to change the line.
>sed '/unix/ c "Change line"' file.txt
"Change line"
linux
"Change line"
"Change line"
linux
"Change line"
root@ctx2p02:/var/tmp#
Interview Questions: