Linux Material
Linux Material
LINUX
INDEX
Part-1: UNIX/LINUX Concepts & Commands …………………………………………………………………… 4
Topic-35: Stream
Part-3: Linux Editor (SED)Basics
Administration ………… …
………
………
……
………
………
…………
………………
………………
…………………
………
………
………
…………
…………
……
229 Topic-36:
260 AWK Programming … ……… ………… …… …… … …… … …… … … ……… …… …… …………….
233
Topic-38: Job Scheduling with crontab ………………… Topic-37:
……………… Project
…………on ……awk
………programming
…………….
… … …… … … … …… …… …… …… ……… …… … … ………… … 248
262 Topic-39: User Management …………………………………………………………………………………….
.266 Topic-40: Working with putty,Mobaxterm and XShell
………………………………………………… 276 Topic-41: How to customize Open Source Software
Code …………………………………………… 280 Topic-42: Process Management
…………………………………………………………………………………. 236 Topic-43: Communication
Commands (write,wall,msg, mail) ……………………………………. 240 How to use Gmail from
the Ubuntu Terminal to send Emails ……………………………………… 243 Topic-44: Package
Management …………………………………………………………………………………. 246 Topic-45: Install
and Working with MySQL Database …………………………………………………. 250 Topic-46:
Working with Java ………………………………………………………………………………………. 257 Topic-47:
Job Control ………………………………………………………………………………………………….. 259 Topic-
48: nohup command …………………………………………………………………………………………. 262
Topic-49: at command ………………………………………………………………………………………………… 263
Topic-50: Memory related commands ………………………………………………………………………… 265
Topic-51: Networking commands ………………………………………………………………………………. 270
Topic-52: Working with winscp ……………………………………………………………………………………
273 Topic-53: Working with Filezilla …………………………………………………………………………………..
274 Topic-54: init command
……………………………………………………………………………………………… 275 Topic-55: Top Most
important Linux Questions ………………………………………………………….276
Part-1
UNIX / LINUX
Concepts
&
Commands
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Agenda
Topic-1: Overview of UNIX/Linux Operating System
Topic-13: Piping
Topic-18: Compression and Uncompression of files (tar, gzip, gunzip, bzip2, bunzip2)
Topic-22:DURGASOFT,
Working with
# 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5 editors 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Topic-1: Overview of
UNIX/Linux Operating System
What is UNIX?
Flavours of UNIX
Components of UNIX
Online Terminal Demo with some basic commands
What is UNIX?
✽ It is an operating system, by using that, users/applications can communicate with hard
ware components.
✽ It was developed/created in 1960s.
✽ With lot of extensions and improvements to base version, several flavours introduced
by organization/companies (flavours like Redhat linux, ubuntu, CentOS etc)
Features of UNIX:
1) It is FOSS (Freeware and Open Source Software)
2) UNIX can be used by multiple users simultaneously and hence it is Multi User
operating System.
3) Several tasks can be executed simultaneously and hence it is multi tasking operating
system.
4) It is user friendly and provides both CUI and GUI Support.
5) When compared with windows, UNIX is more secured.
Flavours of UNIX:
As UNIX is open source, multiple flavours are available with lot of extensions and
improvements.
Ubuntu
RedHat
Centos
Fedora
Slackware
open solaries
Suse Linux Enterprise server (SLES)
Open Suse
Components of UNIX
Shell:
✽ It is the outer layer of UNIX operating System.
✽ It reads our command, verify syntax and check whether the corresponding command
related application is available or not.
✽ If everything is proper, then shell interprets our command into kernal understandable
form and handover to the kernal.
✽ Shell acts as interface between user and kernal.
Kernal:
✽ It is the core component of UNIX operating system.
✽ It is responsible to execute our commands.
✽ It is responsible to interact with hardware components.
✽ Memory allocation and processor allocation will takes care by kernal.
Topic-2: Linux
File System
Types of Files in Linux:
In Linux everything is treated as File.
All files are divided into 3 types
2) Directory Files:
These files represent directories.
In windows, we can use folder terminology where as in linux we can use directory
terminology.
Directory can contains files and sub directories.
3) Device Files:
In Linux, every device is represented as a file. By using this file we can communicate
with that device.
Note: c, b, s are representing system files and mostly used by super user (also known as
root user or admin user)
2) $ cd .
Changes to Current Directory (Useless)
3) $ cd ..
Changes to Parent Directory
4) $cd
If we are not passing any argument, then changes to user home directory.
5) $ cd ~
~ Means User Home Directory.
It will Changes to User Home Directory.
6) $ cd -
- Means Previous Working Directory.
It will Changes to Previous Working Directory.
durgasoft@durgasoft:~/Downloads/coreutils-8.31/src$ pwd
/home/durgasoft/Downloads/coreutils-8.31/src
durgasoft@durgasoft:~/Downloads/coreutils-8.31/src$ cd ~
durgasoft@durgasoft:~$ pwd
/home/durgasoft
durgasoft@durgasoft:~$ cd -
/home/durgasoft/Downloads/coreutils-8.31/src
durgasoft@durgasoft:~/Downloads/coreutils-8.31/src$
pwd DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
11 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
/home/durgasoft/Downloads/coreutils-8.31/src
durgasoft@durgasoft:~/Downloads/coreutils-8.31/src$ cd . . / . . / . .
durgasoft@durgasoft:~$ pwd
/home/durgasoft
1) bin Directory:
bin means binary. This directory contains all binary executables related to our linux
commands.
2) sbin Directory:
sbin means systembin. It contains all binary executables related to high end admin
(super user OR root) commands.
Eg: Disk partitioning, network management etc
3) etc Directory:
This directory contains all system configuration files. These configurations can be used
to customize behaviour of linux os.
All users information available in /etc/passwd file.
All groups information available in /etc/group file.
Hosts information (ip address and dns names) available in /etc/hosts file.
4) tmp Directory:
tmp means temporary. It contains all temporary files created in the current session.
If any file is required only for the current session, then create that file inside tmp
directory. These files will be deleted automatically at the time of system shutdown.
If any file which is required permanently, then it is not recommended to create inside
tmp directory.
5) dev Directory:
dev means device.
In Linux, everything is treated as a file including devices also. i.e every device is
represented as a file. By using these files, we can communicate with the devices.
All device related files will be stored inside dev directory.
Eg:
tty Terminal related File
fd Floppy Drive related File
hd Hard Disk related File
ram RAM related File
stdin standard Input Device
File (keyboard)
stdout Standard Output Device File (Terminal/Monitor)
stderr Standard Error Device File (Terminal/Monitor)
6) mnt Directory:
mnt means mounting.
We have to attach external file system files from Pen drive, CD, external hard disk etc
to the Linux File System. Then only we can use those external files. This attachment
process is called mounting.
In the old operating systems, we have to perform mounting manually. But in recent
operating systems, mounting is performing automatically and we are not required to
perform manually.
The files of manual mounting will be placed inside mnt directory.
7) media Directory:
The files of automatic mounting will be placed inside media directory.
8) opt Directory:
opt means optional.
This directory contains all 3rd party software installation files.
Eg:
If we are installing any software explicitly like google chrome, then the corresponding
installation files will be stored inside opt directory.
9) lib Directory:
lib means library. It contains Linux os libraries which are required by our commands
and applications.
Note:
/home/durgasoft Is called durgasoft user home directory. It contains multiple sub
directories like Desktop, Downloads, Movies, Pictures etc.
durgasoft@durgasoft:/$ ps - e f
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 11:05 ? 00:00:03 /sbin/init
root 2 0 0 11:05 ? 00:00:00 [kthreadd]
root 3 2 0 11:05 ? 00:00:00 [rcu_gp]
root 4 2 0 11:05 ? 00:00:00 [rcu_par_g
....
Note:
/home/durgasoft Durgasoft User Home Directory
/root Super User Home Directory
Note:
16) The main advantage of Linux File System is, operating system can locate required files
very easily.
17) For every File System, a separate name will be assigned.
18) ext2,ext3,ext4,XFS are names of Linux File Systems.
19) NTFS, FAT are names of Windows File Systems.
Topic-3: Linux
Installation
1) Oracle Virtual Box Installation
2) Virtual Machine Installation with Ubuntu OS
Various Utilities:
1) To make Full Screen: Devices Insert Guest Additions CD Image
2) To open terminal: ctrl+alt+t
3) To close terminal: ctrl+d
4) To increase font in terminal: ctrl+shift+plus symbol
5) To decrese font in terminal: ctrl+ minus symbol
6) To copy and paste from windows to ubuntu and from ubuntu to windows:
Devices Shared Clipboard Bidirectional
7) To drag and drop files from windows to ubuntu and from ubuntu to windows:
Devices Drag and Drop Bidirectional
man ls
It provides complete information about ls command.
2) ls -r
It will display all files and directories in reverse of aplhabetical order.
3) ls | more
To display content line by line
(To come out we have to use q)
4) ls | pg
To display content page by
page.
Each page contains 20 lines of content.
(To come out we have to use q)
5) ls -l
To display long listing of files
6) ls -t
To display all files based on last modified date and time. Most recent is at top and old
are at bottom.
7) ls -rt
To display all files based on reverse of last modified date and time. Old files are at top
and recent files are at bottom.
8) ls -a
a means all
To display all files including hidden files. Here . and .. also will be displayed.
9) ls -A
A means almost all
To display all files including hidden files except . and ..
durga@durga-VirtualBox:~$ l s - a
. msmtp.log
.. .msmtprc
.bash_history Music
.bash_logout .mysql_history
.bashrc Pictures
.cache .profile
.config Public
.dbus script1.sh
durga@durga-VirtualBox:~$ l a -A
.bash_history .msmtprc
.bash_logout Music
.bashrc .mysql_history
.cache Pictures
.config .profile
.dbus Public
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
10) ls -F
To display all files by type.
directory /
executable file *
link file @
Eg:
initctl@ Link File
pts/ Directory
ls* Executable File
11) ls -f
To disable colors
12) ls -i
To display all files
including inode
number.
i-node is the address of
location, where file
attributes are stored.
i-node is the address of
the location, where file
attributes are stored.
13) ls -R
R means Recursive.
It will list all files and directories including sub directory contents also. By default ls
will display only direct contents but not
# 202, 2nd Floor, subMaitrivanam,
directory contents.
20 DURGASOFT,
HUDA Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
14) ls -s Maii: [email protected]
$ ls /dev | less
$ ls /dev | more
If we want only fixed number of files either from top or from bottom we have to use head
and tail commands with ls commands.
Note: We can use these options simultaneously. When ever using options simultaneosuly
then the order is not important.
Q1) Write the Command to display all Files including Hidden Files in Last Modifiction Time
Order. Oldest should be First and recent should be Last. It should include Inode
Number and the Number of Blocks used by that File. The Output should be in Long
listing Form?
$ ls -atrisl
131279 4 -rw-r--r-- 1 durga durga 807 Jan 3 12:57 .profile
131277 4 -rw-r--r-- 1 durga durga 3771 Jan 3 12:57 .bashrc
162011 4 -rw-r--r-- 1 durga durga 220 Jan 3 12:57 .bash_logout
132496 4 drwx------ 3 durga durga 4096 Jan 3 13:03 .gnupg
132517 4 drwx------ 3 durga durga 4096 Jan 3 13:03 .local
404481 4 drwxr-xr-x 2 durga durga 4096 Jan 3 13:03 Templates
Q2) Which Command will Lists all Files including Hidden Files along with their Inode
Numbers?
ls -ai
Q3) Which Command will make a Long listing of all the Files in our System including
Hidden Files, sorted by Modification Date (Oldest First)?
ls -latr
2)date Command:
We can use date command to display date and
time of system.
Various Options:
1) date +%D
To display only date in the form: mm/dd/yy
2) date +%T
To display only time in the form: hh:mm:ss
3) date +%d
To display only day value
4) date +%m
To display only month value
5) date +%y
To display only year value in yy form
6) date +%Y
To display only year value in yyyy form.
7) date +%H
To display only Hours value (in 24 hours scale format)
8) date +%M
To display only Minutes value
9) date +%S
To display only Seconds value
Eg 2: Create an empty file where file name contains current system date.
touch "durgajobs$(date +%d%m%Y).log"
durgajobs31102019.log
durgajobs01112019.log
durgajobs02112019.log
durgajobs03112019.log
durgajobs04112019.log
Eg 3: Create an empty file where file name contains current system date and time
touch "durgajobs$(date +%d%m%Y%H%M%S).log"
durgajobs31102019205834.log
Note:
If the file name contains date and time then that file is said to be timestamped file (file
with timestamp)
cal Command:
$ cal To display current month calendar.
$ cal 2020 To display total year calendar.
$ cal 1 To display 1st year calendar.
$ cal 9999 To display 9999th year calendar.
$ cal 10000 cal: year '10000' not in range 1..9999
$ cal 08 2019 To display august 2019th calendar
Note: cal command can provide support only for the years 1 to 9999.
1) mkdir dir1
To create a directory
3) mkdir dir1/dir2/dir3
To create dir3. But make sure dir1 and in that dir2 should be available already.
4) mkdir -p dir1/dir2/dir3
-p means path of directories.
All directories in the specified path will be created.
First dir1 will be created and in that dir2 will be created and within that dir3 will be
created.
jan2020
schedule_1.txt
schedule_2.txt
...
schedule_31.txt
$ mkdir heroinesDURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
$ cd 24
heroines 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
$ mkdir sunny katrina kareena
$ mkdir
{sunny,katrina,kareena}/{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}_{2020,2021,20
22}
$ touch
{sunny,katrina,kareena}/{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}_{2020,2021,20
22}/schedule_{1..31}.txt
Case Study-2:
Create 5 directories named with dir6,dir7,dir8,dir9 and dir10. In these directories create
empty files with a.txt,b.txt,c.txt and d.txt
$ mkdir dir{6..10}
$ touch dir{6..10}/{a..d}.txt
Note: *,[],{ } etc are called wild characters. We can use wild card characters in every
command.
Note: rmdir command will work only for empty directories. If the directory is not empty
then we will get error. We cannot use rmdir for files. Hence the most useless (waste)
command in linux is rmdir.
If the directory is not empty then to remove that directory we should use rm command.
All internal content also will be removed. rm command can work for files also. Hence rm is
recommended to use than rmdir.
durga@durga-VirtualBox:~$ rm heroines
rm: cannot remove 'heroines': Is a directory
Whenever we are using rm command for directories, we should use -r or -R option. Here
case is not important.
Note: In Linux operating system, there is no way to perform undo operation. Once we
delete a file or directory, it is impossible to retrieve that. Hence while using rm command
we have to take special care.
The following command is the most dangerous command in linux, because it removes
total file system.
rm -r /
2) force removal(-f):
While removing files and directories, if we don't want any error messages, then we should
use -f option. It is opposite to -i option.
durga@durga-VirtualBox:~$ rm -r dir99
rm: cannot remove 'dir99': No such file or directory
durga@durga-VirtualBox:~$ rm -rf dir99
durga@durga-VirtualBox:~$
3) verbose Option(-v):
If we want to know the sequence of removals on
the screen we should go for -v option.
durga@durga-VirtualBox:~$ rm -r dir6
durga@durga-VirtualBox:~$ rm -rv dir8
removed 'dir8/c.txt'
removed 'dir8/d.txt'
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 'dir8/a.txt'
removed 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
removed Maii: [email protected]
'dir8/b.txt'
UNIX/
LINUX
removed directory 'dir8'
durga@durga-VirtualBox:~$
mkdir dir1/dir2/dir3
Only dir3 will be created and compulsory dir1 and in that dir2 should be avilable
already. If dir1 or dir2 not available then this command won't work.
mkdir -p dir1/dir2/dir3
-p means complete path
All 3 directories will be created.
Ans: C
Ans: B
Q5) Assume that dir1 is non empty Directory and text1 is just a Text File.
Which of the following Command will remove both dir1 and text1
successfully?
rm text1 dir1
rm -v text1 dir1
rm -R text1 dir1
Ans: C
Q7) How to Create a Directory named A and in that a Directory B and inside
that a Directory C?
-$ mkdir -p A/B/C
Q8) How many Directories will be created after running the following
Command?
$ mkdir {a..c}{1..3}
9 Directories named with a1, a2, a3, b1, b2, b3, c1, c2, c3
Note: In file or directory names, it is not recommended to use space. Instead of that we
have to use _ symbol like java_classes.
Case Study:
Write commands to create the following directory structure
1st way:
durga@durga-VirtualBox:~$ pwd
/home/durga
durga@durga-VirtualBox:~$ mkdir x y
durga@durga-VirtualBox:~$ cd x
durga@durga-VirtualBox:~/x$ mkdir x1 x2
durga@durga-VirtualBox:~/x$ cd x1
durga@durga-VirtualBox:~/x/x1$ mkdir
x11 x12
durga@durga-VirtualBox:~/x/x1$ cd ..
durga@durga-VirtualBox:~/x$ cd ..
durga@durga-VirtualBox:~$ cd y
durga@durga-VirtualBox:~/y$ mkdir y1 y2
durga@durga-VirtualBox:~/y$ cd y1
durga@durga-VirtualBox:~/y/y1$ mkdir
y11 y12
2nd way:
$ mkdir x x/x1 x/x2 x/x1/x11 x/x1/x12 y
y/y1 y/y2 y/y1/y11 y/y1/y12
3rd way:
$ mkdir -p x/x1/x11 x/x1/x12 x/x2
y/y1/y11 y/y1/y12 y/y2
4th way:
$ mkdir -p x/x{1,2} x/x1/x1{1,2} y/y{1,2}
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
29
y/y1/y1{1,2} 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
Q14) To Remove Directories where Name Starts with 'd' and Ends with 'n'
$ rmdir d*n
Q15) To Remove Directoreis where Name Starts with 'd' OR 'x' $ rmdir
[dx]*
Absolute Path:
$ cd /home/durga/y/y2
$ cd ~/y/y2
Relative Path:
$
cd
../../../y/y2
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
30 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Eg 2: Assume we are in y2 directory. To change to x11
Absolute Path:
$ cd /home/durga/x/x1/x11
$ cd ~/x/x1/x11
Relative Path:
$ cd
../../x/x1/x11
Eg 3: Assume we are in x11 directory. To create y21 directory inside y2 without enter
into y2 directory.
Absolute Path:
$ mkdir /home/durga/y/y2/y21
$ mkdir ~/y/y2/y21
Relative Path:
$
mkdir
4) Copy Command (cp)
../../../y/y2/y21
$ cp -r dir1 dir2
total dir1 will be copied to dir2
Note:
If the destination directory (dir2) already available then total dir1 will be copied to dir2.
If the destination directory (dir2) not already available, then destination directory will be
created and all files of source directory will be copied to destination directory but source
directory won't be copied.
Q16) Write Command to Copy Data from a.txt, b.txt, c.txt to d.txt?
$ cp a.txt b.txt c.txt d.txt It won't work.
We will discuss solution in the next classes.
1) Renaming of files:
$ mv oldname newname
Eg: $ file1.txt file2.txt
file1.txt will be
renamed to file2.txt
2) Renaming of
Directories:
$ mv dir1 dir2
dir1 will be renamed
to dir2
3) Moving files to
directory:
$ mv a.txt b.txt c.txt
output
a.txt,b.txt and c.txt
will be moved to
output directory.
4) Moving ofDURGASOFT,
all files # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
nd
rmdir dir1
rmdir dir1 dir2 dir3
rm -r dir1
rm -ri dir1
rm -rf dir1
rm -rv dir1
rm -r dir*
rm -r
dir{2..6}
rm -r
dir[2,4]
cp file1.txt
file2.txt
cp file1.txt file2.txt file3.txt output
cp dir1/* dir2
cp -r dir1 dir2
mv file1.txt file2.txt
mv dir1 dir2 (rename b'z dir2 not available)
mv dir1/* dir2
mv dir1 dir2 (move dir1 to dir2 because dir2 available)
cd
cd ../../..
cd /
cd ~
cd -
1) Creation of Files:
In Linux, we can create files in the following ways:
10) By using touch command (to create empty file)
11) By using cat command
12) By using editors like gedit, vi, nano etc
cat Command:
cat > file1.txt
Eg:
$ cat > file1.txt
Hello Friends
Listen Carefully
Otherwise Linux will give Left and Right
ctrl+d To save and exit
If file1.txt is not already available, then file1.txt will be created with our provided data.
If file1.txt is already available with some content, then old data will be over written with
our provided new data.
Instead of overwriting, if we want append operation then we should use >> with cat
command.
Q2) How we can perform overwriting and appending with cat Command?
> meant for overwriting
>> meant for appending/concatenation
Q3) If we are using Touch Comamnd, but the File is already available then
what will happend?
The content of the file won't be changed. But last modified date and time
(i.e., timestamp) will be updated.
durga@durga-VirtualBox:~$ ls -l file1.txt
-rw-r--r-- 1 durga durga 77 Jan 9 12:24 file1.txt
durga@durga-VirtualBox:~$ touch file1.txt
durga@durga-VirtualBox:~$ ls -l file1.txt
-rw-r--r-- 1 durga durga 77 Jan 9 12:33 file1.txt
Use Case:
Assume that we write one shell script. The job of this shell script is to send all current date
files to remote server. Assume that this script won't be executed on sat and sun. But on
Monday all 3 days files have to be send.
But the problem with this script is it can recognize only current date files. To change
timestamp of sat and Sunday files, we have to use touch command.
While viewing file content we can include line numbers by using -n option.
While display file content we can skip blank lines by using -b option.
durga@durga-VirtualBox:~$ cat -n file1.txt
1 This is first
line 2
3 This is second
line 4
5 This is third
line
36 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
6
7
8 This is extra line
2) To append
some extra
data to
existing file
$ cat >> filename
extra data
ctrl+d
3) To view
content of
file
$ cat <
filename or $
cat filename
4) Copy content
of one file to
another file
$ cat
input.txt >
output.txt
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
37copy
5) To 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
content of Maii: [email protected]
multiple files
to a single
UNIX/LINUX
2. tac Command:
It is the reverse of cat.
It will display file content in reverse order of lines. i.e first line will become last line and
last line will become first line.
This is vertical reversal.
3. rev Command:
rev means reverse.
Here each line content will be reversed.
It is horizontal reversal.
Note
:
cat command will display total file content at a time. It is best suitable for small files. If the
file contains huge lines then it is not recommended to use cat command. We should go for
head, tail, less and more commands.
4. head Command:
We can use head command to view top few lines of content.
✽ head file1.txt
It will display top 10 lines of file1.txt.
10 is the default value of number of lines.
5. tail Command:
We can use tail command to view few lines from bottom of the file.
It is opposite to head command.
✽ tail file1.txt
Last 10 lines will be displayed.
✽ tail -n +4 file1.txt
It will display from 4th line to last line
6. more Command:
We can use more command to view file content page by
page.
✽ more file1.txt
It will display first page.
Enter To view next line
Space Bar To view next page
q To quit/exit
✽ more -d file1.txt
-d option meant for providing details like
--More--(5%)[Press space to continue, 'q' to quit.]
7. less Command:
By using more command, we can view file content page by page only in forward
direction.
If we want to move either in forward direction or in backward direction then we
should go for less command.
Eg: Assume a file contains enough data. Write command to display from 3rd Line to 7th
Line.
1) Katrina Kaif
2) Kareena Kapoor
3) Karishma Kapoor
4) Sunny Leone
5) Mallika Sharawath
6) Sonakshi Sinha
7) Alia Butt
8) Pooja
9) Anushka
10) Deepika
head -7 demo.txt
1. Katrina Kaif
2. Kareena Kapoor
3. Karishma Kapoor
4. Sunny Leone
5. Mallika Sharawath
6. Sonakshi Sinha
7. Alia Butt
tail -5 demo.txt
3. Karishma Kapoor
4. Sunny Leone
5. Mallika Sharawath
6. Sonakshi Sinha
7. Alia Butt
touch .securefile1.txt
cat > .securefile1.txt
Even by using editors
also we can create
hidden files.
mkdir .db_info
Note: By using hidden files and directories we may not get full security. To make more
secure we have to use proper permissions. For this we should use 'chmod' command.
mv a.txt .a.txt
We are converting normal file a.txt as hidden file.
directories also mv
dir1 .dir1
mv .dir1 dir1
Copying of Files:
cp file1.txt file2.txt
If file2.txt not available, then file2.txt will be created and the content will be copied.
If file2.txt is already available and contanis some data then that data will be overwritten
with file1.txt data.
Before overwriting if we want confirmation, then we should go for -i option.
i means interactive.
cp -i file1.txt file2.txt
$ cp -i a.txt b.txt
cp: overwrite 'b.txt'?
$ cp -v a.txt b.txt
'a.txt' -> 'b.txt'
cp file1.txt
file2.txt file3.txt
file4.txt output
Note: To copy multiple files content to the single file, we should not use cp command. we
should use cat command.
1) Renaming of Files:
mv oldname newname
mv file1.txt file2.txt
file1.txt will be renamed to file2.txt
2) Renaming of Directories:
mv dir1 dir2
dir1 will be renamed to dir2
Topic-8: Comparing
Files
We can compare data of two files by using the following commands:
1) cmp
2) diff
3) sdiff
4) vidiff
5) comm
1) cmp Comamnd:
It will compare byte by byte.
Note: cmp command won't show all differences and show only first difference.
2) diff Comamnd:
It will show all differences in the content.
For the
diff
comma
nd we
can use
the
$ diff -q a.txt c.txt
followin
Files a.txt and c.txt differ
g$ diff -s a.txt b.txt
options.
Files a.txt and b.txt are identical
-q
$ diff -y a.txt c.txt
shows
Sunny Sunny
message
Bunny | bunny
when
Chinny | chinny
files
Vinnyare Vinny
differen
Pinny Pinny
t.
-s
If we want to suppress common lines then we should use --suppress-common-lines option
shows
with -y option.
message
when
$ diff -y --suppress-common-lines a.txt c.txt
files
Bunny are | bunny
same
Chinny | | chinny
identica
l
3) sdiff Command:
-y
showsWe can use sdiff command for side by side comparison (parallel comparison)
compari
$ sdiff
son linea.txt b.txt
Sunny
by line Sunny
Bunny
(parallel Bunny
Chinny
compari Chinny
Vinny
son) Vinny
Pinny Pinny
$ sdiff a.txt c.txt
Sunny Sunny
Bunny | bunny
Chinny | chinny
Vinny Vinny
Pinny Pinny
Note: sdiff comamnd and diff command with -y option are same.
4) vimdiff Command:
It will highlight differences in vim.
5) comm Command:
By using this command we can compare data of two files.
Pinny
Note: We can compare files from various builds by using our comparison commands
(cmp, diff, sdiff, vimdiff, comm).
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
46 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
RG RA D C Testing Production Build-1 released Test.java RG
RA D C Testing Production Build-2 released Test.java
Case Study:
Requirement-1: assume file1.txt is available inside x11 directory and we are in user home
directory. copy this file to y2 directory.
cp /home/durgasoft/x/x1/x11/file1.txt /home/durgasoft/y/y2
cp ~/x/x1/x11/file1.txt ~/y/y2
cp x/x1/x11/file1.txt y/y2
Requirement-2: assume file1.txt is available inside x11 directory and we are in user home
directory. move this file to y11 directory.
mv /home/durgasoft/x/x1/x11/file1.txt /home/durgasoft/y/y1/y11
mv ~/x/x1/x11/file1.txt ~/y/y1/y11
mv x/x1/x11/file1.txt y/y1/y11
Topic-9: Creation of
Link Files
There are 2 types of link files
1) Hard Link files
2) Soft Link files
$ ln dir1 dir2
ln: dir1: hard link not allowed for directory
Note: For files we can create both hard and soft links. But for directories we can create
only softlinks butnot hardlinks.
Case Study:
Assume dir1 contains dir2.
dir2 contains softlink dir3 pointing to dir1
$ mkdir -p dir1/dir2
$ cd dir1/dir2
$ ln -s ~/Desktop/dir1 dir3
Note: While creating link files there may be a chance of forming loops. Take a bit special
care.
Ans: D
Q2) Which of the following is Valid Way to Create Soft Link for sunny.jpg
Present in Pictures Directory?
A) ln ~/Pictures/sunny.jpg newimg.jpg
B) ln -s ~/Pictures/sunny.jpg newimg.jpg
C) ln newimg.jpg ~/Pictures/sunny.jpg
D) ln -s newimg.jpg ~/Pictures/sunny.jpg
Ans: B
Q3) We can Create both Hard and Soft Links to the Directories. Is it
Valid?
E) True
F) False
Ans: B
Note: If we perform any change to the content of original file, then these changes will be
reflected to the link file. Similarly, if we perform any change to the link file, then those
changes will be reflected to the original file. This is true for both hard and soft links.
wc filename
no_of_lines no_of_words no_of_characters filename
Eg:
$ wc a.txt
4 26 166 a.txt
4 Number of Lines
26 Number of words
166 Number of
characters (File size in
bytes)
-l To print only
number of lines
-w To print only
number of words
-c To print only
number of characters
-lw To print only
number of lines and
words
-lc To print only
number of lines and
characters
-wc To print only
number of words and
characters
-L To print number of
characters present in
Longest Line.
$ wc51
-l a.txt DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 a.txt 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
$
$ wc -w a.txt
26 a.txt
UNIX/
LINUX
$ wc -L a.txt
57 a.txt
We can use
wc
command
for multiple
files
simultaneo
usly.
$ wc a.txt b.txt c.txt
4 26 166 a.txt
3 4 27 b.txt
4 4 112 c.txt
11 34 305 total
Topic-11: Sorting
Content of the File
We can sort data of the file by using sort command.
sort filename
Here sorting is based on alphabetical order.
$ cat a.txt
Sunny
Bunny
Chinny
Vinny
Pinny
$ sort a.txt
Bunny
Chinny
Pinny
Sunny
Vinny
If we want
to sort
based on
reverse of
alphabetic
al order,
then we
should use
-r option.
$ sort -r a.txt
Vinny
Sunny
Pinny
Chinny
Bunny
If the file contains alphanumeric data, then first numbers will be considered and then
alphabet
53 symbols. DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
$ cat a.txt
Maii: [email protected]
7
Sunny
8
UNIX/
LINUX
Chinny
6
Vinny
5
Pinny
$ sort a.txt
1
5
6
7
8
Bunny
Chinny
Pinny
Sunny
Vinny
$ sort -r a.txt
Vinny
Sunny
Pinny
Chinny
Bunny
8
7
6
5
1
If the file contains only numbers, then the sorting is not based on numeric value and it is
just based on digits.
$ sort a.txt
11
2
2222222
7
9
$ sort -n a.txt
2
7
9
11
2222222
Bydefault sort command will display duplicate lines. If we want only unique lines then we
have to use -u option.
-u meant for unique lines.
$ cat a.txt
1
1
2
2
Sunny
Sunny
Bunn
y
$ sort a.txt
1
1
2
2
Bunny
Sunny
Sunny
$ sort -u a.txt
1
2
Bunny
Sunny
Q1) Assume a.txt contains the following Data
Note:Sunny
We Bunny
can Chinny
use - Vinny
ur and
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
-un 55
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
optio Maii: [email protected]
ns
also.
UNIX/
LINUX
Without using -r option with sort command, sort the content based on reverse of
alphabetical order and store the result inside sorted.txt?
Sorting Tabular
Data by using -k
Option:
drwxr-xr-x
-k means KEYDEF3 (key root root 4096 Aug 6 00:34 acpi
-definition).
r w - r - - r -Based
- 1 on
root root
which 3028 Aug 6 00:28 adduser.conf
drwxr-xr-x
key (column) we2have root
to root 4096 Nov 7 19:47 alternatives
-sort.
r w - r - - r - - 1 root root 401 May 29 2017 anacrontab
- r w - r - - r - - 1 root root 433 Oct 2 2017 apg.conf
$ l s - l / e t c |6 head
drwxr-xr-x root -10
root 4096 Aug 6 00:30 apm
tdrwxr-xr-x
o t a l 1068 3 root root 4096 Aug 6 00:33 apparmor
drwxr-xr-x 8 root root 4096 Nov 7 06:32 apparmor.d
drwxr-xr-x 4 root root 4096 Nov 7 06:33 apport
$ cat a.txt
Sunny
sunny
Bunny
Chinny
Sunny
Bunny
Chinny
$ uniq a.txt
Sunny
sunny
Bunny
Chinny
Sunny
Bunny
Chinny
Sunny
With
uniq
comm
and
we
can
use
multi58 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
ple
Maii: [email protected]
optio
ns:
-d
UNIX/
LINUX
1. To display only duplicate lines:
$ sort a.txt | uniq -d
Bunny
Chinny
Sunny
2. To
disp
lay
num
ber
of
occu
rren
ces
of
eac
h
line:
$ sort a.txt | uniq -c
2 Bunny
2 Chinny
1 sunny
2 Sunny
3. To ignore case
while comparing:
$ sort a.txt | uniq -i
Bunny
Chinny
sunny
$ sort a.txt | uniq -ic
2 Bunny
2 Chinny
3 sunny
4. To display only
unique lines i.e
the lines which
are not
duplicated:
$ sort a.txt | uniq -u
sunny
Commands can take input, perform required operation and produces some output.
While executing command if anything goes wrong then we will get error message.
Command can take input either from standard Input or from command line arguments.
Command will produce results to either Standard output or Standard Error.
Standard Input, Standard Output and Standard Error are Data Streams and can flow from
one place to another place. Hence redirection and piping are possible.
Command Line arguments are static and these are not streams. Hence redirection and
piping concepts are not applicable to command line arguments.
Bydefault Standard input connected with keyboard, Standard output and Standard Error
connected with Terminal. But we can redirect.
Note: For the cat command if we are not providing any arguments, then the input will be
taken from standard input device (keyboard) and display the output to the standard
output device (Terminal).
Note: Some commands may accept Standard Input and Some commands may accept
command line arguments.
1) rm command will always accept command line arguments only.
rm file1 file2
2) echo command will always aceept command line arguments only.
echo "durgasoft"
3) cat command can accept input either from standard input or from comamnd line
arguments.
Redirection
As Standard Input, Standard Ouput and Standard Error are Data streams, we can redirect
these streams.
Instead of
overwriting if we
want to perform
appending then
we should use
>>.
Redirecting
Standard
Error:
We can redirect error messages from the terminal to our own file by using > and >>
symbols.
Now error message won't be displayed to the console and will written to error.txt.
For error redirection 2 is mandatory.
***Note: To redirect both standard output and standard error to the same destination we
can use shortcut as follows
termainal - 2:
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
$ tty62
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
/dev/pts/1 Maii: [email protected]
terminal - 1:
UNIX/LINUX
Bits
Q1) In How Many Ways Command can get Input?
2 ways. Either from Standard Input or from command line arguments.
Topic-14: Piping
Sometimes we can use output of one command as input to another command. This
concept is called piping.
By using piping, multiple commands will work together to fulfill our requirement.
$ ls -l /etc | wc
215 1940 11872
First ls got executed and the output of this command will become input to wc command.
Eg 2: $ ls -l /etc | more
Eg 3: $ ls -l /etc | wc |wc -l
The output is: 1
Eg 4: $ ls -l /etc | head -5
Note: instead of ls -l we
can use ll command, most
of linux flavours provides
tee Command:
support.
Requirement:
The output of the ls command should be saved to output.txt and should be provided as
input to wc command:
ls -l 1>output.txt | wc
This command won't work because if we are using redirection in the middle of piping, it
will break piping concept.
In piping, if we want to save the output of one command to a file and if we want to pass
that output as input to next command simultaneously, then we should go for tee
command.
Eg 2: To save the output of ls command to a file and send that output as input to wc
command
$ ls -l | tee output.txt | wc -l
xargs Command:
Q1) Display the Output of Date Command by using echo
Command with Piping Concept?
$ date | echo It won't work because the output of date command is stream, but echo
command will accept only command line arguments but not stream.
$ date | xargs echo xargs command will convert the output stream of date
command into command line arguments and these arguments will be passed as
input to echo command.
Hence the job of xargs command is to convert output stream into command line
arguments
Eg 1: Assume input.txt contains file names. Each file contains some data.
Read file names from the input.txt, write total content to output.txt and display the total
number of lines present in output.txt.
Eg 2: Assume input.txt contains file names. Read file names from the input.txt and remove
all these files.
Assignment:
list out all contents of /dev folder and save to file1.txt.
list out all contents of /bin folder and save to file2.txt.c
Q4) How we can use tee Command when Piping together Commands A, B
and C to save Output of B Command to results.txt.
A | B | tee results.txt | C
Q5) How to Pipe Data from Command A to Command B, but B won't accept
Standard Input and accepts only Command Line Arguments?
A | xargs B
First cmd1 will be executed and then cmd2 followed by rest of the commands.
If any command fails in the middle, still rest of the commands will be executed.
First cmd1 will be executed and then cmd2 followed by rest of the commands.
If any command fails in the middle, then rest of the commands won't be executed.
Eg:
create a directory dir1
create files a.txt,b.txt,c.txt in that dir1
write current system date and time to a.txt
write current month calendar to b.txt
mkdir dir1 ; touch dir1/{a,b,c}.txt ; Date > dir1/a.txt ; cal > dir1/b.txt
Here 3rd command fails, but still 4th command will be executed.
mkdir dir1 && touch dir1/{a,b,c}.txt && Date > dir1/a.txt && cal > dir1/b.txt
Here 3rd command fails, and hence 4th command won't be executed.
A wildcard character can be used as a substitute for required sequence of characters in the
regular expression.
22) To list out all files starts with a and ends with t $ ls a*t
24) To list out all files where file name contains only 2 characters and first character
should be 'a' $ ls a?
8) To list out all files where file name contains atleast 3 characters $ ls ???*
9) To list out all files where file name starts with a or b or c $ ls [abc]*
10) To list out all files where file name should not starts with a, b and c $ ls [!abc]*
11) To list out all files starts with lower case aphabet symbol
$ ls [a-z]* OR $ls [[:lower:]]*
12) To list out all files starts with upper case aphabet symbol
$ ls [A-Z]* OR $ls [[:upper:]]*
14) To list out all files where first letter should be upper case alphabet symbol, second
letter should be digit and third letter should be lower case alphabet symbol.
$ ls [[:upper:]][[:digit:]][[:lower:]]
16) To list out all files with .java and .py extension
$ ls {*.java, *.py}
Note: We can use these wildcard characters with the following commands also.
cp, mv, rm
18) To move all files starts with alphabet symbol and with .txt extension to dir2
directory?
$mv [[:alpha:]]*.txt dir2
Q1) Which of the following Command will List all Files that has
exactly 3 Characters Present in Current Working Directory?
A) ls ***
B) ls ???
C) ls !!!
D) ls &&&
Ans: B
Q2) Which of the following Commands will Copy all Files that Ends
with .pdf to dir1?
E) cp ?.pdf dir1
F) cp .pdf* dir1
G) cp *.pdf dir1
Ans: C
Q3) Which of the following Command will move all the Files that
begins with Letter a and Ends with Letter n to dir1?
$mv a*n dir1
Q5) Which of the following Commands will List all Files that begins
with a Lower Case Alphabet Symbol and has a Letter d in the
3rd Character Position, and Ends with an Upper Case Letter?
$ls [[:lower:]]?d*[[:upper:]]
Q6) Which of the following Command will List all .jpg Files Present
in Pictures Directory?
$ls /home/durgasoft/Pictures/*.jpg
$ls ~/Pictures/*.jpg
Q7) Which of the following Regular Expressions will Match the File
named with demoA.txt ?
A) *
B) demo?.txt
C) demo*
D) *.txt
E) demo[A-Z].txt
F) All of these
student_reportC.pdf
G) ??.pdf
H) report*.pdf
I) *[A-Z].pdf
J) student*.pdf
Ans: C, D
Topic-17: Command
Aliasing
Alias means other alternative name or nickname.
We can give our own more convinient nicknames for unix commands. This concept is
called command aliasing.
Note: we can use type command, to check whether the command is already available or
not.
After aliasname space is not allowed. Hence the following are invalid
alias nickname ='original command'
alias nickname= 'original command'
alias nickname = 'original command'
alias cls='clear'
alias rename='mv'
alias grpe='grep'
4. To handle language
barriers:
In Germany datum means
date.
alias datum='date'
How to persist
aliases
permanently?
Whatever aliases we created, are bydefault available only in the current session. Once we
close the terminal, all aliases will be lost.
But we can make our created aliases permanently in our system by using the following 2
ways:
1st Way:
We have to define our aliases in .bashrc file present in our home directory.
gedit .bashrc
# myown aliases
alias cls='clear'
alias ddd='date;date;date'
Note: To reflect
these aliases,
compulsory we
have to close and
open terminal.
Q1) What is
the Purpose of
Alias
Comamnd?
To list out all
available
aliases and to
create new
alias.
Q2) How to
Use Unalias
Command?
unalias alias_name To remove a particular alias
unalias –a To remove all aliases
Ans: D
Internally locate command will search in the database for the required files and
directories and returns the results.
To ignore case:
By default locate command will consider case. If we want to ignore case, we have to use -i
option.
$locate -i *.jpg
We can limit the number of lines in the result by using --limit option.
$ locate --limit 5 *.conf
/etc/adduser.conf
/etc/apg.conf
/etc/appstream.conf
/etc/brltty.conf
/etc/ca-certificates.conf
Before display results, to check whether the file exists or not , we have to use -e option or
--existing option.
$ locate -S
Database /var/lib/mlocate/mlocate.db:
39,527 directories
3,69,078 files
2,42,42,520 bytes in file names 93,40,974
bytes used to store database
This database will be updated only once per day. If we are creating or removing files and
directories, to reflect these changes we have to update database explicitly by using
updatedb command. But admin privileges must be required.
$ sudo updatedb
[sudo] password for durgasoft:
Q3) We created a File called demo.txt. But it has been 2 Hours since locate
Database has been updated. Is locate Command able to find this
demo.txt?
H) Yes
I) No
Ans: No
find Command:
We can use find command to find files and directories present in our system.
It provides more search options when compared with locate command like
1) Search only files
2) Search only directories
3) Search by name
4) Search by size
5) We can use search results automatically for some other
commands
6) We can restrict maxdepth
etc
1. $find
It will find all files and directories in current working directory and below in linux file
system. This is the default behaviour.
# 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
79 DURGASOFT,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
2. We can find all files and directories in the specified directory and below.
$ find /dev
$ find /etc
3. maxdepth Option:
usually find command will search in all depth levels. But we can specify the required depth
level by using maxdepth option.
Desktop
|-file1.txt
| -l e v e l _ 1 _ d i r
|-file2.txt
|-levlel_2_dir
|-file3.txt
| -l e v e l _ 3 _ d i r
|-file4.txt
| -l e v e l _ 4 _ d i r
|-file5.txt
$mkdir -p level_1_dir/level_2_dir/level_3_dir/level_4_dir
$touch file1.txt level_1_dir/file2.txt level_1_dir/level_2_dir/file3.txt
level_1_dir/level_2_dir/level_3_dir/file4.txt
level_1_dir/level_2_dir/level_3_dir/level_4_dir/file5.txt
4. $ find . -maxdepth 1
5. $ find . -maxdepth 2
6. $ find . -maxdepth 3
7. $ find . -maxdepth 4
8. $ find . -maxdepth 100
Note:
9. For maxdepth option we should use singl - but not double --
-maxdepth Valid
--maxdepth Invalid
2. find command will find hidden files and directories also.
Find by Type:
We can find only files or only directories by using type option.
-type f means only files
-type d means only directories
Note: We can use these options simultaneously, but we should use first -maxdepth and
then -type.
Find by Name:
We can find files and directories by name by using -name option.
$ touch {A..D}.txt
$ touch {A,B}{A,B}.txt
2. To list out all file names where size is over 200kb but less than 4MB.
$ find / -type f -size +200k -size -4M | wc -l
3. To list out all file names where file size is less 200kb or more than 4MB.
$ find / -type f -size -200k -o -size +4M | wc -l
-o means or
Note:
+n for greater than n
-n for less than n
n for exactly n
-empty File is
empty and is
either a regular file
or a directory
Q2) How to
Use Search
Results of
Find
Command?
We can perform any operation (like cp, mv, rm etc) on the results of find command.
For this we have to use -exec option.
-exec means execution.
Q3) To Copy all Files Present in /etc Folder where File Size is
< 2KB to dir1 Directory Present in the Desktop?
nd
Magic Assignment:
$ mkdir magic
$ mkdir magic/dir{1..100}
$ touch magic/dir{1..100}/file{1..100}.txt
Q4) The Find Command Uses a Database to Search Files and Directories
A) True
B) False
Ans: B
Q5) To find Files and Directories inside /dev Folder and Limit its Search to
only 2 Levels of Deep?
C) find -start /dev -depth 2
D) find /dev -depth 2
E) find /dev -maxdepth 2
Ans: C
Q6) To find only Directories inside /dev Folder and Limit its Search to only 2
Levels of Deep?
F) find /dev -maxdepth 2 -type f
G) find /dev -maxdepth 2 -type d
H) find /dev -type d -maxdepth 2
Ans: B
Q7) To find only Files Starts from Root Directory (/) where File Name Ends
with .txt?
I) find / '*.txt'
J) find / -type d -name '*.txt'
K) find / -type f -name '*.txt'
Ans: C
Q8) To find all Files and Directories inside /dev Directory upto Maximum of 3
Levels Deep and Size is Greater than 200 Kilo Bytes?
A) find / -maxdepth 3 -size 200k
B) find /dev -maxdepth 3 -size 200k
C) find /dev -maxdepth 3 -size -200k
D) find /dev -maxdepth 3 -size +200k
Ans: D
Q9) Which of the following Command will find all Files below our Home
Directory where File Size is Greater than 3 Mega Bytes and Remove all
those Files?
E) find ~ -type f -size +3M -exec rm {} \;
F) find ~ -type f -size -3M -exec rm {}
G) find ~ -type f -size -3M -exec rm {} \;
H) find ~ -type f -size +3M rm {} \;
Ans: A
6)Creation of Archive
File
We can group multiple files and directories into a single archive file by using tar
command.
2)Apply
Compression
Algorithms on that
Archive File:
There are multiple compression
and
85 decompression
DURGASOFT,algorithms.
# 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
3) gzip It is very fast
Maii: [email protected]
but less compression
power
4) bzip2 It is a bit
UNIX/LINUX
2) To uncompress gz file:
$ gzip -d demo.tar.gz OR $ gunzip demo.tar.gz
This command will provide our original tar file
How to create
tar File and
compress in a
Single
Command:
3. By using gzip
compression algorithm
To uncompress and
extract tar file
$ tar -xvzf demo.tar
$mkdir newhome
$mv backup.tar newhome
$cd newhome
$ tar -xvzf backup.tar
Topic-20: grep
Command
grep stands for
globally search a regular expression and print it
global regular expression print.
global regular expression parser.
We can use grep command to search the given pattern in a single or multiple files.
$ grep durga *
career.txt:durga
career.txt:durga
subjects.txt:3. unix
ksdjfdlakjklfjad durga 250
subjects.txt:5. UNIX durga 400
subjects.txt:6. Java durga 1000
Eg 1:
durgasoft@durgasoft:~/Desktop$ grep -i unix demo.txt
UnixDemo session
unix material
durgasoft@durgasoft:~/Desktop$ grep -iw unix demo.txt
unix material
-A means after
-B means before
-C means before and after
Note: C is optional.
Instead of using -e
option, we can use egrep
command directly.
It is extended grep. It
interprets patterns as an
extended reqular
expression.
grep with -F
Option OR
fgrep:
fgrep "Fixed String
Global Regular
Expression Print"
It will take a group of fixed strings and search for those in the given file. Strings should be
separated by new line.
Eg:
durgasoft@durgasoft:~/Desktop$ cat demo.txt
This is java demo
UnixDemo session
unix material
UNIX classes and videos
java is slowly going down
(java|unix) this is extra line added
durgasoft@durgasoft:~/Desktop$ grep -i "(java|unix)" demo.txt
(java|unix) this is extra line added
In this case (java|unix) is considered as a string and cannot be processed as regular
expression.
In this case, (java|unix) is treated as regular expression. It will search for either java or
unix.
egrep and fgrep are deprecated and hence it is recommend to use grep -E and grep -F
commands.
If strings are available in the file, then we can use -f option to specify file name.
file1.txt
java
unix
python
demo
-i,-n,-c,-
v,-l,-A,-
B,-C,-e,-
E, -F,-f, -
o, -R
To
Prin
t
only
mat
che
d
Patt
erns
inst
ead
of
Tota
l
Line DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
94
: 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
We
have to
UNIX/
LINUX
call center
cell point
college for
unix
durgasoft@durgasoft:~/Desktop$ fgrep c[aeiou]ll demo.txt
c[aeiou]ll point for fgrep
durgasoft@durgasoft:~/Desktop$ egrep c[aeiou]ll demo.txt
call center
cell point
college for unix
resumes
java
students.txt
python
students.txt
testing
students.t
xt
$ mkdir
resumes
Note: If we want to use grep command for directory, compulsory we should use -
R option, which means recursive.
Assignment:
1. Save all running processes information inside a file.
$ ps -ef > results.txt
5. Display all lines which contain 'lib' and preceding with line numbers?
$ grep -n 'lib' results.txt
6. Display lines which do not contain 'lib', but only top 2 lines.
$ grep -v 'lib' results.txt | head -2
Assignment-2:
durgasoft@durgasoft:~/Desktop$ cat emp.dat
eno|ename|esal|eaddr|dept|gender 100|
sunny|1000|mumbai|admin|female 200|
bunny|2000|chennai|sales|male 300|
chinny|3000|delhi|accounting|female 400|
vinny|4000|hyderabad|admin|male 500|
pinny|5000|mumbai|sales|female
1) Character Patterns
2) Word Patterns
3) Line Patterns
4) Character Patterns:
1) $ grep 'd*' demo.txt
It display all lines which contains d followed by any number of characters.
ubuntu not providing support for this.
2) Word Patterns:
\<word\> It will always searches for the given word
It is exactly same as
grep -w word demo.txt
3.{m,n} The preceding character should match minimum m times and maximum n
times.
$ egrep -o '\
<[0123][0-9][-/]
[01][0-9][-/][0-9]
{4}\>' input.txt
emp.dat eno|ename|esal|eaddr|dept|
gender 100|sunny|1000|mumbai|admin|
female 200|bunny|2000|chennai|sales|
male 300|chinny|3000|delhi|accounting|
female 400|vinny|4000|hyderabad|
admin|male 500|pinny|5000|mumbai|
sales|female
1) Display Character on
specific Position in every
Record:
$ cut -c 9 emp.dat
-c meant for specific character
e
2) D
i
s
p
l
a
y
102 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
R
UNIX/
LINUX
3) $Display
cut -d '|' -fSpecific
3 emp.dat Column Data:
-d means delimiter (separator). The default delimiter is tab.
-f means field
It will display 3rd Field (OR Column ) data.
paste Command:
We can use paste command to join two or more files horizontally by using some delimiter.
Default delimiter is tab.
Eg:
durgasoft@durgasoft:~/Desktop$ cat > subjects.txt
Core Java
Adv Java
Python
Django
Note: Delimiter should be only one character. If we are providing more than one
character, then it will consider only first character.
tr Command:
tr means translate.
This command translates character by character.
Topic-22: File
Permissions
File Permissions describe the allowed operations by various users.
With respect to file permissions, all users are categorized into the following 4 types.
User Categories:
user/owner Represented by 'u'
group Represented by 'g'
others Represented by 'o'
all Represented by 'a'
Use Case to
understand Types of
Users:
Project: DURGASOFT COLLEGE
AUTOMATION SYSTEM
This project divided into multiple modules. In each module multiple deverlopers are
working.
1) STUDENTS MODULE
A, B, C, D ARE WORKING
2) EMPLOYEES MODULE
X, Y, Z ARE WORKING
3) COURSES MODULE
M, N ARE WORKING
4) INFRASTRUCTURE MODULE
G, H ARE WORKING
For demo.txt
user/owner: A (The person who created the file)
group: B,C,D (The persons who are working in the same module)
others: X,Y,Z,M,N,G,H (The persons who are working on other modules)
Permission Types:
For files and directories, there are 4 types of permissions.
1) r Read
2) w Write
3) x Execute
4) - No Permission
Table_FilePermissions
chmod Command:
chmod means change mode.
We can use chmod command to change file or directory permissions.
Note: Only owner and super user (root) can change file permissions.
durgasoft@durgasoft:~/Desktop$ ls -l
total 0
-rw-r--r-- 1 durgasoft durgasoft 0 Nov
27 21:19 demo.txt
Total 9 permissions. First 3 are user permissions, next 3 are group permissions and next 3
are others permissions.
Read
Permission to
the File:
If the file not having read permission then we are not allowed to view content of the file.
Hence cat, head, tail, more, less commands won't work.
durgasoft@durgasoft:~/Desktop$ ls -l
total 4
-rw-r--r-- 1 durgasoft durgasoft 34 Nov 28 20:56 demo.txt
durgasoft@durgasoft:~/Desktop$ cat demo.txt
This is file content at beginning
durgasoft@durgasoft:~/Desktop$ chmod u-r demo.txt
durgasoft@durgasoft:~/Desktop$ ls -l first.sh
-rw-r--r-- 1 durgasoft durgasoft 82 Nov 28 21:10 first.sh
durgasoft@durgasoft:~/Desktop$ ./first.sh
bash: ./first.sh: Permission denied
durgasoft@durgasoft:~/Desktop$ chmod u+x first.sh
durgasoft@durgasoft:~/Desktop$ ls -l first.sh
-rwxr--r-- 1 durgasoft durgasoft 82 Nov 28 21:10 first.sh
durgasoft@durgasoft:~/Desktop$ ./first.sh
Hello Friends...
File Permissions is very very important than Sunny
durgasoft@durgasoft:~/Desktop$ ls -l
total 4
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 28 21:18 dir1
durgasoft@durgasoft:~/Desktop$ ls dir1
demo.txt first.sh
durgasoft@durgasoft:~/Desktop$ chmod u-r dir1
durgasoft@durgasoft:~/Desktop$ ls -l
total 4
d-wxr-xr-x 2 durgasoft durgasoft 4096 Nov 28 21:18 dir1
durgasoft@durgasoft:~/Desktop$ ls dir1
ls: cannot open directory 'dir1': Permission denied
durgasoft@durgasoft:~/Desktop$
durgasoft@durgasoft:~/Desktop$ ls -l
total 4
dr-xr-xr-x 2 durgasoft durgasoft 4096
Nov 28 21:18 dir1
durgasoft@durgasoft:~/Desktop$ touch dir1/newfile.txt
touch: cannot touch 'dir1/newfile.txt': Permission denied
durgasoft@durgasoft:~/Desktop$ rm -f dir1/demo.txt
rm: cannot remove 'dir1/demo.txt': Permission denied
durgasoft@durgasoft:~/Desktop$ chmod u+w dir1
durgasoft@durgasoft:~/Desktop$ ls -l
total 4
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 28 21:18 dir1
durgasoft@durgasoft:~/Desktop$ touch dir1/newfile.txt
durgasoft@durgasoft:~/Desktop$ rm -f dir1/demo.txt
durgasoft@durgasoft:~/Desktop$ ls dir1
first.sh newfile.txt
durgasoft@durgasoft:~/Desktop$ ls -l
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 28 21:26 dir1
durgasoft@durgasoft:~/Desktop$ chmod u-x dir1
durgasoft@durgasoft:~/Desktop$ ls -l
total 4
drw-r-xr-x 2 durgasoft durgasoft 4096 Nov 28 21:26 dir1
\durgasoft@durgasoft:~/Desktop$ cd dir1
bash: cd: dir1: Permission denied
durgasoft@durgasoft:~/Desktop$ chmod u+x dir1
durgasoft@durgasoft:~/Desktop$ cd dir1
***Note: If the user not having execute permission on any directory, then he cannot
perform read and write operations also, because to perform these operations he should
enter into that directory which is not possible.
Note: If the user not having read permission on any file, then he cannot execute that file
even though he has executed permission.
Linux vs Security:
The virus files usually created by others.
others are not having execute permission on our directories. Hence others are not allowed
to add virus files to our directories.
Hackers are not having executed permission on our directories. Hence they cannot read
our file data.
Note: We are using permission types as r,w,x and these are considered as symbolic
permissions. But we can also specify permissions by using octal number, such type of
permissions are called numeric permissions.
Numeric Permissions:
We can specify permissions by using octal number.
Octal means base-8 and allowed digits are 0 to 7.
1 000 No Permission
2 001 Execute Permission
3 010 Write Permission
4 011 Write and execute Permissions 4
100 Read Permission
5 101 Read and execute Permissions 6
110 Read and write Permission
7 111 Read, Write and execute
Permissions
Note:
4 Read Permission
2 Write Permission
1 Execute
Permission
$ chmod 77 demo.txt
durgasoft@durgasoft:~/Desktop$ ls -l demo.txt
----rwxrwx 1 durgasoft durgasoft 0 Nov 29
20:57 demo.txt
77 means 077
$ chmod 7 demo.txt
durgasoft@durgasoft:~/Desktop$ ls -l demo.txt
-------rwx 1 durgasoft durgasoft 0 Nov 29 20:57
demo.txt
7 means 007
$ chmod demo.txt
durgasoft@durgasoft:~/Desktop$ chmod demo.txt
chmod: missing operand after ‘demo.txt’
Try 'chmod --help' for more information.
$ chmod 0 demo.txt
durgasoft@durgasoft:~/Desktop$ ls -l demo.txt
---------- 1 durgasoft durgasoft 0 Nov 29 20:57
demo.txt
umask Command:
umask means user mask. Hiding permissions.
Based on umask value,default permissions will
be there for files and directories.
The default umask value:022
durgasoft@durgasoft:~/Desktop$ umask
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
114
0022
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
First 0 is sticky bit mostly used in admin related activities. We have to consider only last 3
digits as umask value.
UNIX/
LINUX
Default permissions to the file: 666 - umask value
= 666 - 022
= 644 (user r&w, group read, others read)
durgasoft@durgasoft:~/Desktop$ ls -l file1.txt
-rw-r--r-- 1 durgasoft durgasoft 0 Nov 29 21:18 file1.txt
$ mkdir dir1
$ ls -l
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 29 21:21 dir1
chown Command:
chown means change owner.
Only root user can perform this activity.
chgrp Command:
chgrp means change group.
Only root user can perform this activity.
durgasoft@durgasoft:~$ sudo -i
[sudo] password for durgasoft:
root@durgasoft:~#
root@durgasoft:~# whoami
root
root@durgasoft:~# cd /home/durgasoft/Desktop
root@durgasoft:/home/durgasoft/Desktop# ls
demo.txt
root@durgasoft:/home/durgasoft/Desktop# ls -l
total 0
-rw-r--r-- 1 durgasoft durgasoft 0 Nov 29 21:33 demo.txt
root@durgasoft:/home/durgasoft/Desktop# chown root demo.txt
root@durgasoft:/home/durgasoft/Desktop# ls -l
total 0
-rw-r--r-- 1 root durgasoft 0 Nov 29 21:33 demo.txt
root@durgasoft:/home/durgasoft/Desktop#
Case Study:
-rwxrw-r-- 1 root durgasoft 42 Nov 30 19:47 demo.txtowner: root
group: durgasoft
Group members can perform both read and write operations.
Eg 2:
-rwxrwxr-- 1 root root 90 Nov 30 19:55 demo.txt
owner: root
group: root
others can perform only read operation.
duragsoft user can perform only read operation
durgasoft@durgasoft:~/Desktop$ cat demo.txt
Group Permissions:
durgasoft durgasoft
Others Permissions:
-rwxrwxr-- 1 root root 114 Nov 30 20:22 demo.txt
Topic-23: Working
with Editors
We can use editors to edit file content.
There are multiple editors are available.
1) geditor
2) vi editor
3) nano editor
etc
1)working with
geditor:
It is graphical editor. It
is simply same as
window's notepad.
$ gedit file1.txt
$ gedit first.sh
Note: gedit can work only in the desktop version and cannot work in server version.
By using putty if we are connecting remote server, then we cannot use gedit and
compulsory we should go for vi editor.
vi editor is unix based where as gedit and nano are linux based.
vi can work anywhere.
$ vi file1.txt
If file1.txt is not available, then a new file will be created and opened that file for
editing purpose.
To save this empty file we should use :wq (w means save and q means exit)
If the file already contains some data then editor will be opened that file and ready for
edit.
1) Command Mode:
It is the default mode.
Here we can use any vi command.
From command mode, we can enter into insert mode by using multiple ways, but
mostly by using i.
3) Exit Mode:
To quit from the editor.
From the command mode we have to press: then we can enter into exit mode.
Deletion Line
wise:
dd To delete current line
3dd To delete 3 lines
d$ Deletes from current
position to end of line.
d^ Deletes from current
position to beginning of the
line.
dgg Deletes from beginning of the file to current cursor position.
Dg Deletes from current position to end of file.
We are not required to use these because keyboard arrow keys aleady working.
b(nb) Back to beginning of the Word
3b Back to beginning of the 3rd (ie 3rd previous Word)
e(ne) End of the Current Word
w(nw) Forward to beginning of next Word.
at exit mode
:1 To go to 1st line
:7 To go to 7th line
Note: If we want to perform undo previous operation then we should use 'u'
u Means undo previous operation
Eg:
:!date To check system date
:!cal To check calander
Note: vi +7 demo.txt
open demo.txt and enter into 7th line
Various Options:
ctrl+g (F1) Display this help text
ctrl+x (F2) Close the current file buffer / Exit from nano
ctrl+o (F3) Write the current file to disk
ctrl+r (F5) Insert another file into the current one
Part-2
Shell Scripting
Agenda
Topic-24: Shell Scripting / Shell Programming:
Topic-30: Operators
Topic-32: Arrays
Types of Shells:
There are multiple types of shells are available.
1) Bourne Shell:
It is developed by Stephen Bourne.
This is the first shell which is developed for
UNIX.
By using sh command we can access this
shell.
2) BASH Shell:
BASH Bourne Again SHell.
It is advanced version of Bourne Shell.
This is the default shell for most of the linux flavours.
By using bsh command we can access this shell.
3) Korn Shell:
It is developed by David Korn.
Mostly this shell used in IBM AIX operating system.
By using ksh command, we can access this shell.
4) CShell:
Developed by Bill Joy.
C meant for California University.
It is also by default available with UNIX.
By using csh command, we can access this shell.
5) TShell:
T means Terminal.
It is the advanced version of CShell.
This is the most commonly used shell in HP UNIX.
By using tcsh command, we can access this shell.
6) Z Shell:
Developed by Paul.
By using zsh command we can access this shell.
Note: The most commonly used shell in linux environment is BASH. It is more powerful
than remaining shells.
We can
also
check the
default
shell
informati DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
on126 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
inside Maii: [email protected]
/etc/pass
wd file
UNIX/LINUX
$ cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/bin/rbash
/bin/dash
durgasoft@durgasoft:~/Desktop$ sh
$ echo $0
sh
$ exit
durgasoft@durgasoft:~/Desktop$ echo $0
bash
durgasoft@durgasoft:~/Desktop$ rbash
durgasoft@durgasoft:~/Desktop$ echo $0
rbash
durgasoft@durgasoft:~/Desktop$ exit
exit
durgasoft@durgasoft:~/Desktop$
dash
$ echo $0
dash
$ exit
Inside shell script, we can also use programming features like conditional statements,
loops, functions etc. Hence we can write scripts very easily for complex requirements also.
demo.sh:
echo "Welcome to shell script"
date
cal
$ /bin/bash ./demo.sh
$ bash ./demo.sh
$ /bin/bash
/home/durgasoft/scripts/dem
o.sh
$ ./demo.sh # default shell
is bash
Note: The default shell is bash. Hence bash is responsible to execute our script.
Instead of bash, if we want to use Bourne shell then we have to use the following
command
$ /bin/sh ./demo.sh
$ sh ./demo.sh
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
128 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
Importance of Sha-Bang:
By using sha-bang, we can specify the interpreter which is responsible to execute the
script.
# Sharp
! Bang
#! Sharp Bang or Shabang or Shebang
If we write shabang in our script at the time of execution, we are not required to provide
command to execute and we can execute script directly.
Without Shabang:
$ python3 ./test.py
$ python3 /home/durgasoft/scripts/test.py
With Shabang:
$ ./test.py
$ /home/durgasoft/scripts/test.py
Q3) Write and Run Shell Script that Prints Current System
Date and Time
date.sh
#! /bin/bash
echo "The current System Date and Time:" date
If we add our script location to PATH Variable value, then we can run our script
from anywhere in our system. We can do this in the following two ways:
1)Session Level:
durgasoft@durgasoft:~/scripts$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/
games:
/snap/bin
$ export PATH=$PATH:/home/durgasoft/scripts
Now we can run our script from anywhere. We are not required to provide either absolute
path or relative path.
$date.sh
The current System Date and Time:
Wed Dec 4 21:01:49 IST 2019
export PATH=$PATH:/home/durgasoft/scripts
Topic-26: Shell
Variables
Variables are place holders to hold values.
Variables are key-value pairs.
In Shell programming, there are no data types. Every value is treated as text type/ String
type.
1)Environment Variables:
These are predefined variables and mostly used internally by the system. Hence these
variables also known as System variables.
But based on our requirement, we can use these variables in our scripts.
We can get all environment variables information by using either env command or set
command.
durgasoft@durgasoft:~$ env
LANG=en_IN
USERNAME=durgasoft
USER=durgasoft
PWD=/home/durgasoft
HOME=/home/durgasoft
SHELL=/bin/bash
LOGNAME=durgasoft
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/
games:/snap/bin:/home/durgasoft/scripts
...
durgasoft@durgasoft:~$ set
BASH=/bin/bash
durgasoft@durgasoft:~$
durgasoft@durgasoft:~$ PS1=DURGA$
DURGA$ls
abc.txt Documents d.txt Pictures scripts Videos y
Desktop Downloads Music Public Templates x
DURGA$cat > abc.txt
asdfjkasjfdsa
asfdkasklfdjlads
DURGA$PS1=Sunny#
Sunny#ls -l
total 52
-rw-r--r-- 1
durgasoft
durgasoft
31 Dec 5
20:58
abc.txt
Demo Script to Use some Environment Variables:
drwxr-xr-x
2
env.sh
durgasoft
#! /bin/bash
durgasoft
echo
4096 "User
Dec 5 Name: $USER"
echo
18:04"User Home Directory: $HOME"
echo "Default Shell Name: $SHELL"
Desktop
echo "PATH: $PATH"
drwxr-xr-x
2
$chmod
durgasoft755 env.sh
$./env.sh
durgasoft
User
4096 Name:
Nov durgasoft
21 17:06
User Home Directory:
Document
/home/durgasoft
s 133 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
drwxr-xr-x Maii: [email protected]
2
durgasoft
durgasoft
UNIX/
LINUX
Default Shell Name: /bin/bash
PATH:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:
/snap/bin:/home/durgasoft/scripts
durgasoft@durgasoft:~/scripts$ GUEST=Dhoni
durgasoft@durgasoft:~/scripts$ echo "Hello $GUEST You are my Hero"
Hello Dhoni You are my Hero
If the variable is readonly then we cannot perform reassignment for that variable.It will
become constant.
Variable Scopes:
There are 3 scopes available for variables.
1) Session Scope
2) User Scope
3) System Scope
4) Session Scope:
The variables which are declared in the terminal are said to be in session scope.
Once we close the terminal (ie exit session) automatically all variables will be gone.
$ X=10
$ Y=10
2) User Scope:
The variables which are declared inside .bashrc file, are said to be in user scope.
These variables are available for all sessions related to current user. These variables
cannot be accessed by other users.
.bashrac
....
export GUEST=Dhoni
export FRIEND=Sunny
3) System Scope:
If the variable available for all users and for all sessions, such type of variables are said
to be in system scope.
...
export NAME=DURGA
export COURSE=PYTHON
Syntax:
$variablename
${variablename}
test.sh
#! /bin/bash
a=10
b=20
COURSE="linux"
ACTION="SLEEP"
echo "Values of a and b are: $a and $b"
echo "My Course is: ${COURSE}"
echo "My Favourite Action:
$ACTIONING"
echo "My Favourite Action: $
{ACTION}ING"
Output:
Values of a and b are: 10 and 20
My Course is: linux
My Favourite Action:
My Favourite Action: SLEEPING
Ans: B, D
durgasoft@durgasoft:~/scripts$ NAME='durga'
durgasoft@durgasoft:~/scripts$ echo NAME
NAME
durgasoft@durgasoft:~/scripts$ echo $NAME
durga
durgasoft@durgasoft:~/scripts$ echo
'$NAME'
$NAME
durgasoft@durgasoft:~/scripts$ echo "$NAME"
durga
Command Substitution:
We can execute command and we can substitute its result based on our requirement by
using command substitution.
Syntax:
Old style: `command ` These are backquotes butnot single quotes
New Style: $(command)
Eg 1:
durgasoft@durgasoft:~/scripts$ echo "Today Date is: `date +%D` "
Today Date is: 12/06/19
durgasoft@durgasoft:~/scripts$ echo "Today Date is: $(date +%D) "
Today Date is: 12/06/19
Eg 2:
durgasoft@durgasoft:~/scripts$ echo "Number of files in Current Working Directory: `ls |
wc -l` "
Number of files in Current Working Directory: 5
durgasoft@durgasoft:~/scripts$ echo "Number of files in Current Working Directory: $(ls |
wc -l) "
Number of files in Current Working Directory: 5
Eg 3:
durgasoft@durgasoft:~/scripts$ echo "The No of Lines in test.sh: `cat test.sh | wc -l` "
The No of Lines in test.sh: 9
durgasoft@durgasoft:~/scripts$ echo "The No of Lines in test.sh: $(wc -l test.sh) "
The No of Lines in test.sh: 9 test.sh
Topic-28: Command
Line Arguments
The arguments which are passing from the command prompt at the time of executing our
script, are called command line arguments.
The command line arguments are learning, linux, is, very, easy.
Eg:/bin/bash
#! test.sh
echo "Number of arguments: $#"
echo "Script Name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"
echo "Fourth argument: $4"
echo "Fifth argument: $5"
echo "Total arguments: $*"
IFS="-"
test.sh
#! /bin/bash
l=$(echo -n "DURGA"| wc -c)
echo "The Length of given String: $l"
test.sh
#! /bin/bash
len=$(echo -n "$1"| wc -c)
echo "The Length of given string $1 : $len"
This script will work for any string provided from command prompt.
durgasoft@durgasoft:~/scripts$ test.sh
The Length of given string : 0
durgasoft@durgasoft:~/scripts$ test.sh durgasoft
The Length of given durgasoft : 9
durgasoft@durgasoft:~/scripts$ test.sh adsfkjshfdjkhsfkjhkjsfhk
The Length of given string adsfkjshfdjkhsfkjhkjsfhk : 24
test.sh
#! /bin/bash
echo "Enter A Value:"
read A
durgasoft@durgasoft:~/scripts$ test.sh
Enter A Value:
100
Enter B Value:
200
A Value: 100
B Value: 200
test.sh
#! /bin/bash
echo -n "Enter A Value:"
read A
Approach-2
#! /bin/bash
read -p "Enter A Value:" A
read -p "Enter B Value:" B
durgasoft@durgasoft:~/scripts$ test.sh
Enter A Value:100
Enter B Value:200
A Value: 100
B Value: 200
#! /bin/bash
read -p "Enter User Name:" user
read -p "Enter Password:" password
durgasoft@durgasoft:~/scripts$ test.sh
Enter User Name:durga
Enter Password:anushka123
durga thanks for your information
Note:
read -p : Just to display prompt
message
read -s : It hides input on screen
which is provided by end user.
#! /bin/bash
read -p "Enter User Name:" user
read -s -p "Enter Password:" password
echo
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
143
echo "Hello $user , thanks
for your
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
information" Maii: [email protected]
UNIX/
LINUX
durgasoft@durgasoft:~/scripts$ test.sh
Enter User Name:Durga
Enter Password:
Hello Durga , thanks for your
information
emp.txt
durgasoft@durgasoft:~/scripts$ cat emp.txt
100:Sunny:1000:Mumbai
200:Bunny:2000:Hyderabad
300:Chinny:3000:Chennai
Q4) Write a Script that takes a String from the End User and
Print its Length?
#! /bin/bash
read -p "Enter any string to find length:" str len=$
(echo -n $str | wc -c)
echo "Length of $str : $len"
Q5) Write a Script to Read File Name from the End User and
display its Content?
#! /bin/bash
read -p "Enter any File name to display its content:" fname echo
"-----------------------------------------------"
cat $fname
echo "-----------------------------------------------"
durgasoft@durgasoft:~/scripts$ test.sh
Enter any File name to display its content:emp.txt
-----------------------------------------------
100:Sunny:1000:Mumbai
200:Bunny:2000:Hyderabad
300:Chinny:3000:Chennai
----------------------------------------------
-
Q6) Write a Script to Read File Name from the End User and
Remove Blank Lines Present in that File?
#! /bin/bash
read -p "Enter any File name to remove blank lines:" fname grep -
v "^$" $fname > temp.txt
mv temp.txt $fname
echo "In $fname all blank lines deleted"
Q7) Write a Script to Read File Name from the End User and
Remove Duplicate Lines Present in that File?
#! /bin/bash
read -p "Enter any File name to remove duplicate lines:" fname
Topic-30: Operators
1)Arithmetic Operators
+ Addition
- Substraction
* Multiplication (we should use \* as it is wild card character)
/ Division
% Modulo Operator
Logical Operators:
-a Logical AND
-o Logical OR
! Logical Not
Assignment operator =
Note: Except assignment operator, for all operators we have to provide space before and
after operator.
#! /bin/bash
read -p "Enter First Number:" a
read -p "Enter First Number:" b
sum=`expr $a + $b`
echo "The Sum: $sum"
sum=$(expr $a + $b)
echo "The Sum: $sum"
let sum=$a+$b
echo "The Sum: $sum"
Here $ symbol is optional. But we should not provide
space before and after +.
3) By using (()):
sum=$((a+b))
echo "The Sum: $sum"
sum=$(($a+$b))
echo "The Sum: $sum"
Here space and $ symbol, both are optional.
4) By using []:
sum=$[a+b]
echo "The Sum: $sum"
sum=$[$a+$b]
echo "The Sum: $sum"
bc Command:
bc means binary calculator.
We can start binary calculator by using bc command.
durgasoft@durgasoft:~/scripts$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998,
2000, 2004, 2006, 2008, 2012-2017
Free Software
Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
10.5+30.6
41.1
10.2^2
104.0
10.5*3.6
37.8
ctrl+d To exit bc
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter First Number:10.5
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
149
Enter Second Number:5.3 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
The Sum:15.8 Maii: [email protected]
The Difference: 5.2
The Product: 55.6
UNIX/LINUX
( echo $n | cut -c 1)
b=$( echo $n | cut -c 2) c=$
( echo $n | cut -c 3)
d=$( echo $n | cut -c 4)
annual_salary=$[salary*12] bonus=$
[annual_salary*25/100] echo
"The Bonus:$bonus"
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
150
durgasoft@durgasoft:~/scripts$
88 85test.sh
25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Enter Employee Monthly Salary:10000
Maii: [email protected]
The Bonus:30000
UNIX/
LINUX
9)if Statement:
There are 4 types of if statements
1) simple if
2) if-else
3) nested if
4) ladder if
1) simple if:
if [ condition ]
then
action
fi
If condition is
true then
only action
will be
executed.
Q1) WAS to Read Name from the End User and if Name is
Sunny then Display some Special Message?
#! /bin/bash
[ $name = "sunny" ]
then
echo "Hello Sunny Very Good Evening" fi
echo "How
Enterare you"
Your Name:durga
durgasoft@durgasoft:~/scripts$
151 DURGASOFT, # 202, 2test.sh
nd
Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
How are you
durgasoft@durgasoft:~/scripts$ test.sh
Enter Your Name:sunny
Hello Sunny Very Good Evening
How are you
Note:
x=10 Assignment x
= 10 Comparison
2) if -else:
if [ condition]
then
action if
cond
ition
is
true
else
action if
cond
ition
is
false
fi
3) Nested if:
if [ condition ]
then
.........
.........
if [ condition ]
then
.........
.........
else
........
fi
.....
else
......
fi
4) ladder -if:
if [condition]
then # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
152action-1 DURGASOFT,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
elif [ condition ] Maii: [email protected]
then
action-2
UNIX/
LINUX
else
default action
fi
if [ $a -gt $b ]
then
echo
"Greater
Number
is:$a"
else
echo
"Greater
Number
is:$b"
fi
durgasoft@durgasoft:~/scripts$ test.sh
Enter First Number:10
Enter Second Number:20
Greater Number is:20
durgasoft@durgasoft:~/scripts$ test.sh
Enter First Number:20
Enter Second Number:10
Greater Number is:20
durgasoft@durgasoft:~/scripts$ test.sh
Enter First Number:-10
Enter Second Number:-20
Greater Number is:-10
if [ $a -gt $b ]
then
if [ $a -gt $c ]
then
echo "The Greater Number:$a"
else
echo "The Greater Number:
$c"
fi
elif [ $b -gt
$c ] then
echo "The Greater Number:$b"
else
echo "The Greater Number:
$c"
fi
2nd Way:
#! /bin/bash
if [ $a -gt $b -a $a -gt
$c ] then
echo "The Greater Number: $a"
elif [ $b -gt $c ]
then
echo "The Greater Number: $b"
else
echo "The Greater Number:
$c"
fi
if [ $a -lt 35 ]
then
echo "Student Failed"
elif [ $b -lt 35 ]
then
echo "Student Failed"
elif [ $c -lt 35 ]
then
echo "Student Failed"
else
echo "Result is
Pass"
fi
2nd Way:
#! /bin/bash
The Funniest
Example with if-
else
#! /bin/bash
durgasoft@durgasoft:~/scripts$
./test.sh Enter Your Favourite Brand:KF
It is Childrens Brand
durgasoft@durgasoft:~/scripts$ ./test.sh
Enter Your Favourite Brand:KO
It is not that much Kick
durgasoft@durgasoft:~/scripts$ ./test.sh
Enter Your Favourite
Brand:RC It is too light
durgasoft@durgasoft:~/scripts$
./test.sh Enter Your Favourite Brand:FO
Buy One Get One FREE
durgasoft@durgasoft:~/scripts$
durgasoft@durgasoft:~/scripts$ ./test.sh
Enter Your Favourite Brand:KALYANI
Other Brands are not recommended
exit Command:
In the script to stop execution in the middle, we
can use exit command.
Syntax:
exit status_code
The allowed values for status_code are 0 to 255.
256 0
257 1
258 2
259 3
....
Q5) Write a Script that takes 2 Integer Numbers as Command Line Arguments
and Prints Sum
If Number of Arguments is not 2, then we have to get Message saying
"You should provide only 2 Arguments"
If the Arguments are not Integer Numbers then we have to get Message
saying "You should provide Integer Numbers only"
test.sh
#! /bin/bash
if [ $# -ne 2 ]
then
echo "You Should provide exactly two arguments"
exit 1
fi
x=$1
y=$2
sum=`expr $x + $y `
if [ $? -ne 0 ]
then
echo "You should provide integer numbers only"
exit 2
else
echo "The Sum:$sum"
fi
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
157 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Output:
durgasoft@durgasoft:~/scripts$ test.sh 10 20
The Sum:30
durgasoft@durgasoft:~/scripts$ test.sh
You Should provide exactly two arguments
durgasoft@durgasoft:~/scripts$ test.sh 10
You Should provide exactly two arguments
durgasoft@durgasoft:~/scripts$ test.sh 10 20 30
You Should provide exactly two arguments
durgasoft@durgasoft:~/scripts$ test.sh 10 durga
expr: non-integer argument
You should provide integer numbers only
Output:
durgasoft@durgasoft:~/scripts$
test.sh Enter integer number to
check:10
10 is +ve number
durgasoft@durgasoft:~/scripts$ test.sh
Enter integer number to check:-10
-10 is -ve number
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter integer number to check:10
10 is even number
durgasoft@durgasoft:~/scripts$ test.sh
Enter integer number to check:15
15 is odd number
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter integer number to check:123
123 is 3-dgit number
durgasoft@durgasoft:~/scripts$ test.sh
Enter integer number to check:45
45 is not 3-digit number
durgasoft@durgasoft:~/scripts$ test.sh
Enter integer number to check:1234
1234 is not 3-digit number
if [ -e $fname ]
then
echo "$fname exists"
else
echo "$fname not
exists"
fi
if [ -e $fname ]; then
if [ -f $fname ]; then
if [ -r $fname ]; then
cat $fname
else
echo "User not
having Read
permission"
fi
else
e
c
h
o
"
I
t
i
s
n
o
t
a
r
e
g
u
l
a
r DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
161 fi 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
l
e
"
UNIX/
LINUX
else
echo "It is not a regular file"
fi
else
echo "$fname does not exist"
fi
Note:
-z is string comparison option.
returns True if the string is empty.
READ=NO
WRITE=NO
EXECUTE=NO
if [ -r $fname ]; then
READ=YES
fi
if [ -w $fname ]; then
WRITE=YES
fi
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
162 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
if [ -x $fname ]; then
EXECUTE=YES
fi
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter First File Name: a.txt
User Permissions
Summary
Read Permission: YES
Write Permission: YES
Execute Permission: NO
Q12) Write a Scirpt that Reads File Name and Remove the
specified File?
#! /bin/bash
Mini Application:
Copy all files and directories present in the first directory to the second directory. We
should create compressed tar file and have to move that tar file.
After moving tar file to the second directory, extract all files and directories and remove
that tar file.
copy /home/durgasoft/x /home/durgasoft/y
Tests to Perform:
1) The number of command line arguments should be 2
2) The source and destination directories should be available already
3) The source and destination arguments should be directories
4) The user should has read and execute permissions on source directory
5) The user should has write and execute permissions on destination directory
6) All error messages should be send to error file and the file name should contain
timestamp.
7) All intermediate steps should be displayed to the terminal.
Note:
elif [ $str1 \< $str2 ]; then
If we are not using \ symbol then < acts as input redirection operator. To consider <
as symbol only we should use \.
durgasoft@durgasoft:~/scripts$
test.sh Enter First String:Durga
Enter Second
String:Durga Both strings
are equal DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
164
durgasoft@durgasoft:~/ 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
scripts$ test.sh Maii: [email protected]
UNIX/
LINUX
Enter First String:Apple
Enter Second String:Banana
Apple is less than Banana
durgasoft@durgasoft:~/scripts$ test.sh
Enter First String:Banana
Enter Second String:Apple
Banana is greater than Apple
Q13) Write a Script that Checks whether Login User is Root OR not. If Login
User is Root then Display 1st 5 Current Running Processes Information
#! /bin/bash
user=$(whoami)
$str ]; then
echo "Provided input string is empty string"
else
echo "Provided input string is not empty
string" echo "Its length is : $( echo -n $str | wc
-c)"
fi
2)case Statement:
If multiple options are available then it is not recommended to use nested if-else
statements. It increases length of the code and reduces readability.
Syntax:
case $variable in
option1 )
action-1
;;
option2 )
action-2
;;
option3 )
action-3
;;
*)
default action
;;
esac
Note:
1) space is optional while defining options.
2) ;; can be used to come out of case statement.
3) ;; is mandatory for all options except for default option.
4) If we take default option at the beginning, then for any input the same default option
will be executed.
Eg 1: Write a script to read a number from 0 to 9 and print equivalent English word?
#! /bin/bash
case $n in
1) echo "ZERO"
;;
2) echo "ONE"
;;
2) echo "TWO"
;;
3) echo "THREE"
;;
4) echo "FOUR"
;;
5) echo "FIVE"
;;
6) echo "SIX"
;;
7) echo "SEVEN"
;;
8) echo "EIGHT"
;;
9) echo "NINE"
;;
*) echo "Please enter a digit from 0 to 9 only"
esac
$brand in
"KF")
echo "It is childrens brand"
;;
"KO")
echo "It is not that much kick"
;;
Q16) Write a Script that Accepts a Single Character and Check whether the
given Character is Alphabet OR Digit OR Special Character?
#! /bin/bash
$ch in
[a-zA-Z])
echo "It is an Alphabet symbol"
;;
[0-
9])
e
c
h
o
"
I
t
i
s
a
D
i
g
it
"
;
;
[
^a-
zA-
Z0-9])
e
c
h
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
168 o
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
"
I
t
UNIX/LINUX
Q17) Write a Script that Accepts a Single Character and Checks whether it is
Digit OR Special Character OR Vowel OR Consonent?
#! /bin/bash
case $ch in
[^a-zA-Z0-9])
echo "It is a Special Character"
;;
[0-9])
e
ch
o
"It
is
a
Di
git
"
;
;
[a
eiou
AEIO
U])
e
ch
o
"It
is
a
Vo
w
el"
;
;
[^
aeiou
AEIO
U])
e
ch
o
"It
is
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
169a
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Co Maii: [email protected]
ns
on
en
UNIX/
LINUX
The file name is abc.txt
#! /bin/bash
echo "A Display Content"
echo "B Append Content"
echo "C Overwrite Content"
echo "D Delete Content"
read -p "Choose Your Option
A|B|C|D: " option
case $option in
A)
if [ ! -s "abc.txt" ]; then
echo "It is an empty file"
else
case $option in
1)
echo "$n1 +
$n2 = $
((n1+n2))
"
;;
2)
echo "$n1 -
$n2 = $
((n1-
n2))"
;;
3)
echo "$n1 *
$n2 = $
((n1*n2))
"
;;
4)
echo "$n1 /
$n2 = $
((n1/n2))
"
;;
*)
echo
"Choose
only 1|
2|3|4.
Execute
Again"
esac
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
171 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Iterative Maii: [email protected]
Stateme
UNIX/LINUX
1) while Loop:
If we don't know the number of iterations in advance, then we should go for while
loop.
Syntax:
while [ condition ]
do
body
done
As long as condition is true, then body will be executed. Once condition fails then
only loop will be terminated.
i=1
while [ $i -le
10 ] do
echo $i
let i++
done
while [ $i -le $n ] do
echo $i
sleep
2 let
i++
done
Note: If we don't want to perform any operation for a particular amount of time (i.e just
pausing is required) then we should go for sleep command. The argument to the sleep
command is seconds.
i=1
sum=0
while [ $i -le $n ]
do
let sum=sum+i
let i++
done
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter n value:3
The Sum of first 3 numbers: 6
durgasoft@durgasoft:~/scripts$ test.sh
Enter n value:10
The Sum of first 10 numbers: 55
durgasoft@durgasoft:~/scripts$ test.sh
Enter n value:12345
The Sum of first 12345 numbers:
76205685
while [ true ]
do
clear
printf "\n\n\n\n\n\n\t\t\t\t$(date +%H:%M:%S)"
sleep 1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173
done 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Note: To use escape characters like \n and \t, we should not use echo and we should use
printf command.
Note: true and false are keywords which represents boolean values.
break Statement:
Based on some condition, if we want to break loop execution (i.e to come out of loop)
then we should go for break statement.
Eg 1:
#! /bin/bash
i=1
while [ $i -le 10 ]
do
if [ $i -eq 5 ]; then
break
fi
echo $i
let i++
done
Output
:
1
2
3
4
Eg 2:
#!
/bin/bas
h
while [ true ]
do
clear
printf "\n\n\n\n\n\n\t\t\t\t$(date +%H:%M:%S)"
sleep 1
h=$(date +%H)
m=$(date +%M)
if [ $h -eq 20 -a $m -eq 35 ]; then
break
fi
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
174
done 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
continue Statement:
We can use continue statement to skip current iteration and continue for the next
iteration.
Eg:
#! /bin/bash
i=0
while [ $i -lt 10 ]
do
let i++
if [ $[i%2] -eq 0 ]; then
continue
fi
echo $i
done
Outp
ut:
1
3
5
7
9
Writ
ea
Script
to
Read
File
Nam
e and
Displ
ay its
Conte
nt?
#!
/bin/bas DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
h
175 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
while
[ true ] do
UNIX/
LINUX
continue
;; [nN]|
[nN][oO])
brea
k
;;
esac
done
ech
o
"Thank
s for
using
applica
tion"
Out
put:
durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to Display content: abc.txt
Python
Do you want to display content of another file [Yes|
No]:y Enter File Name to Display content: a.txt
Write a Script that Reads a String as Input and find its Reverse?
Write a Script that performs Reverse of given String?
#! /bin/bash
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter any string to find reverse: durga
The Original String: durga
The Reversed String: agrud
durgasoft@durgasoft:~/scripts$ test.sh
Enter any string to find reverse:
abc The Original String: abc
The Reversed String: cba
durgasoft@durgasoft:~/scripts$ test.sh
Enter any string to find reverse: durgasoft
The Original String: durgasoft
The Reversed String:
tfosagrud
durgasoft@durgasoft:~/scripts$
Eg:
#! /bin/bash
while
177 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
[ true ] do
Maii: [email protected]
clear
tput cup
7 25
UNIX/
LINUX
echo "UNIX/LINUX CLASSES"
sleep 2
done
Note:
tput cup
7 25
It
moves
the
cursor
position
to 7th
row and
25th
column.
while
[ true ] do
read -p "Employee Number: "
eno read -p "Employee Name: "
ename
read -p "Employee Salary: " esal
read -p "Employee Address: " eaddr
echo "$eno:$ename:$esal:$eaddr" >>
emp.txt echo "Employee Record Inserted
Successfully"
read -p "Do you want to insert one more record [Yes|No]: "
option case $option in
[yY]|[Yy][eE][sS])
continue
;; [nN]|
[nN][oO])
brea
k
;;
esac
done
ech
o
"Open
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
178
emp.tx
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
t to Maii: [email protected]
see all
emplo
yees
UNIX/
LINUX
Do you want to insert one more record [Yes|No]: Yes
Employee Number: 300
Employee Name: Chinny
Employee Salary: 3000
Employee Address: Hyderabad
Employee Record Inserted
Successfully
Do you want to insert one more record [Yes|No]: YES
Employee Number: 400
Employee Name: Vinny
Employee Salary: 4000
Employee Address: Chennai
Employee Record Inserted
Successfully
Do you want to insert one more record [Yes|No]: N
Open emp.txt to see all employees information
Syntax -1: To read data from the file by using while loop
cat emp.txt |
while read line
do
do something with that line
done
test.sh
#! /bin/bash
fname=$1
if [ ! -f $fname ]; then
echo "Please provide already existing regular file
only" exit 1
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
179
fi
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
count=1
while read line
do
echo " $count
$line" let count++
done < $fname
Output
durgasoft@durgasoft:~/scripts$ test.sh emp.txt
1 100:Sunny:1000:Hyderabad
2 200:Bunny:2000:Mumbai
3 300:Chinny:3000:Hyderabad
4400:Vinny:4000:Chennai
durgasoft@durgasoft:~/scripts$ test.sh abcd.txt
Please provide already existing regular file only
2) until Loop:
It is opposite to while loop.
Syntax:
until [ condition ]
do
body
done
The body will be executed as long as condition returns false. Once condition returns
true, then loop will be terminated.
durgasoft@durgasoft:~/scripts$
test.sh 1
2
3
4
5 nd
3) for Loop:
If we want to perform some action for every item in the given list, then we should go for
for loop. It is similar to Java's for-each loop.
Syntax:
for variable in item1 item2 item3... itemN
do
action
done
for i in 1 2 3 4
5 do
echo "Current Number: $i"
done
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4
Current Number: 5
Eg 2:
#! /bin/bash
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Course Name: java
Course Name: unix
Course Name: python
Course Name: testing
Course Name:
datascience
Q8) Write a Script that Display Numbers from 1 to 100, which are
divisible by 10.
#! /bin/bash
count=0
for num in {1..100}
do
if [ $[ num%10 ] -eq 0 ]; then
echo "$num"
let count++
fi
done
ech
o
"The
num
ber
of
valu
es:
$cou
nt"
Ou
tput
:
durgasoft@durgasoft:~/scripts$
test.sh 10
20
30
40
50
60
70
80
90
100
The number of values: 10
for name in DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
182
* do 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
if [ -f $name ]; then
echo $name
fi
UNIX/LINUX
Q11) Write
a Script
that Print
all
Command
Line
Arguments
?
#! /bin/bash
if [ $# -ne 0 ];
then
count=1
for arg in $@
do
echo
"Comman
d Line
Argument
- $count:
$arg"
let count++
done
else
echo
"Command line
arguments are
not passed"DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
183
fi 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
Output:
durgasoft@durgasoft:~/scripts$ test.sh
UNIX/
LINUX
Case Study:
emp.txt:
100:sunny:1000:Hyderabad
200:bunny:2000:Chennai
300:chinny:3000:Hyderabad
400:vinny:4000:Delhi
500:pinny:5000:Hyderabad
done
3) W
r
i DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
184
t 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
e
a
UNIX/
LINUX
if [ $sal -gt $max ]; then
max=$sal
max_record=$record
fi
if [ $sal -lt $min ]; then
min=$sal
min_record=$record
fi
done
ech
o
"The
Maxi
mum
Salar
y:
$ma
x"
echo "The Maximum Salaried Employeed Information:"
echo "Employee No:$(echo $max_record | cut -d ":" -f 1)"
echo "Employee Name:$(echo $max_record | cut -d ":" -
f 2)"
echo "Employee Salary:$(echo $max_record | cut -d ":" -f 3)"
echo "Employee Address:$(echo $max_record | cut -d ":" -f 4)"
echo
echo "The Minimum Salary:$min"
echo "The Minimum Salaried Employeed Information:"
echo "Employee No:$(echo $min_record | cut -d ":" -f 1)"
echo "Employee Name:$(echo $min_record | cut -d ":" -f
2)" echo "Employee Salary:$(echo $min_record | cut -d ":" -f
3)"
echo "Employee Address:$(echo $min_record | cut -d ":" -f
4)"
if [ $# -ne 0 ]; then
for fname in
$@ do
if [ -f $fname
]; then
echo
"$fname
content:" # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
185 echoDURGASOFT, 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
"========== Maii: [email protected]
==========
="
UNIX/LINUX
if [ $# -ne 0 ]; then
for fname in $@
do
if [ -f
$fname ]; then
cat $fname >> result.txt
else
echo "$fname does
not exist or it is not a
regular file"
fi
done
else
echo
"Please
pass
atleast
one file
name"
fi
Altern
ative
Syntax
of for
Loop
(Advanc
ed for
Loop):
Old
Style of
for Loop:
for variable in item1 item2 ...
itemN do
body
done DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
186 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Adv Maii: [email protected]
ance
UNIX/
LINUX
Output:
0
1
2
3
4
Q16)
Write
a
Script
to
Displa
y nth
Table?
#!
/bin/bash
read -p "Enter n value:"
n for ((i=1; i<=10; i++))
do
echo "$n * $i = $[n*i]"
done
durga@durga-VirtualBox:~/scripts$
test.sh Enter n value:9
9*1=9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9 187
* 5 = 45
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
9 * 6 = 54 Maii: [email protected]
9 * 7 = 63
9 * 8 = 72
UNIX/LINUX
#! /bin/bash
echo "Welcome to DURGA HOTEL"
echo
amount=0
while [ true ]
do
echo "Menu Items:"
echo "......................"
echo "A --->Vadapov
(Each Plate Rs 30 /-)"
echo "B --->Dosa (Each Plate Rs 50 /-)"
echo "C --->Poori (Each Plate Rs 40 /-)"
echo "D --->Idli (Each Plate Rs 25 /-)"
read -p "Choose Your Required Item A|B|C|D:" item
case $item in
A)
read -p "Enter the number of plates of Vadapov, you required:" quantity
amount=$[amount+quantity*30]
;;
B)
read -p "Enter the number of plates of Dosa, you required:"
quantity amount=$[amount+quantity*50]
;;
C)
read -p "Enter the number of plates of Poori, you required:"
quantity amount=$[amount+quantity*40]
;;
D)
r
e
a
d
-
p
" DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
188
E 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
n Maii: [email protected]
t
e
UNIX/
LINUX
[Yy]|[Yy][Ee][Ss])
continue
;;
[Nn]|[Nn][Oo])
b
reak
;
;
esac
done
echo
echo "Your Total Bill Amount: Rs
$amount/-" echo "Thanks for visiting
DURGA HOTEL"
durga@durga-VirtualBox:~/scripts$
test.sh Welcome to DURGA HOTEL
Menu Items:
……….…………
A Vadapov (Each Plate Rs
30 /-) B Dosa (Each Plate Rs
50 /-)
C Poori (Each Plate Rs
40 /-) D Idli (Each Plate Rs
25 /-)
Choose Your Required Item
A|B|C|D:D
Enter the number of plates of Idli, you
required:4 Do you want to order any other
item[Yes|No]:yes
Menu Items:
……….…………
A Vadapov (Each Plate Rs
30 /-) B Dosa (Each Plate Rs
50 /-)
C Poori (Each Plate Rs
40 /-) D Idli (Each Plate Rs
25 /-)
Choose Your Required Item
A|B|C|D:C
Enter the number of plates of Poori, you
required:3 Do you want to order any other
item[Yes|No]:Yes
Menu
189 Items: DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
……….…………
Maii: [email protected]
A Vadapov (Each Plate Rs
30 /-) B Dosa (Each Plate Rs
50 /-)
UNIX/
LINUX
Menu Items:
……….…………
A Vadapov (Each Plate Rs 30 /-)
B Dosa (Each Plate Rs 50 /-)
C Poori (Each Plate Rs 40 /-)
D Idli (Each Plate Rs 25 /-)
Choose Your Required Item A|
B|C|D:A
Enter the number of plates of Vadapov, you required:1
Do you want to order any other item[Yes|No]:No
2 1, 2
3 1, 3
5 1, 5
#! /bin/bash
read -p "Enter Any Number to test whether it is prime or not:" n
if [ $n -le 1 ]; then
echo "$n is not a PRIME number"
exit 1
fi
for ((i=2;i<=n/2;i++))
do
if [ $[n%i] -eq 0 ];
then
echo "$n is not PRIME number"
exit 1
fi
done
ech
o
"$n
is a
PRI
ME
num
ber"
dur
ga@ DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
190
durg 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
a- Maii: [email protected]
Virtu
alBo
UNIX/
LINUX
Topic-32: Arrays
If we want to represent a group of values with a single name then we should go for arrays
concept.
courses[10]=DataScience
courses[20]=Devops
Demo Script:
#! /bin/bash
courses[0]=Java
courses[1]=Python
courses[2]=Linux
courses[3]=Django
courses[10]=DataScience
Output:
durgasoft@durgasoft:~/scripts$ test.sh
First Element : Java
Second Element : Python
All Elements with @ : Java Python Linux Django DataScience Devops
All elements with * : Java Python Linux Django DataScience Devops
The indices where elements are available : 0 1 2 3 10 20
The total number of elements : 6
The length of first element : 4
Q1) Write a Script to Create an Array with some Elements and Print all
Elements by using while Loop, for Loop and advanced for Loop?
#! /bin/bash
declare -a fruits
fruits=("Apple" "Orange" "Banana" "Mango")
size=${#fruits[@]}
i=0
Output:
durga@durga-VirtualBox:~/scripts$
test.sh All elements by using while loop:
Apple
Orange
Banana
Mango
All
elemen
ts by
using
for
loop:
Apple
Orange
Banana
Mango
All
elemen
ts by
using
advanc
ed for
loop:
Apple
Orange
Banana
Mango
Note
:
1) If we create an array with elements directly
fruits=("Apple" "Orange" "Banana" "Mango")
then the indices will be 0,1,2,3 etc
Q2) Write a Script for accessing Array Elements by using for Loop if
UNIX/
LINUX
echo $fruit
done
echo
echo "Accessing based on
Index:" for index in ${!fruits[@]}
do
echo ${fruits[$index]}
done
Output:
durga@durga-VirtualBox:~/scripts$
test.sh Accessing based on Values:
Apple
Banana
Orange
Mango
Acces
sing
based
on
Index:
Apple
Banana
Orange
Mango
Q3)
Is it
Possi
ble
to
Rem
ove
Arra
y
Elem
ents
? 194 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Y
Maii: [email protected]
e
s
p
UNIX/LINUX
for ((i=0,j=1;i<n;i++))
do
read -p "Enter The Number-$[j++]:" NUM[${i}]
done
Output:
durga@durga-VirtualBox:~/scripts$
test.sh Enter The Number Of values:3
Enter The Number-
1:10 Enter The
Number-2:20
Enter The Number-
3:30
Q5) Write a Script to Read n Numbers and Store inside Array. Print
the Sum of Even Numbers and Odd Numbers separately?
#! /bin/bash
read -p "Enter Number of Values:" n
for((i=0,j=1;i<n;i++))
do
read -p "Enter The Number-$[j++]:" NUM[$i]
done
esum=
0
osum=0
for val in $
{NUM[@]} do
if [ $[val%2] -eq 0 ]; then
let esum=esum+val
else
let osum=osum+val
fi
done
echo "The Sum of Even Numbers:
$esum" echo "The Sum of Odd Numbers:
$osum"
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
195 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Output:
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Number of Values:5
Enter The Number-1:10
Enter The Number-
2:12 Enter The
Number-3:13 Enter
The Number-4:15
Enter The Number-5:20
The Sum of Even Numbers: 42
The Sum of Odd Numbers: 28
Q6) Write a Script to Store all .txt File Names Present in Current Working
Directory in to an Array and Print Permissions of every File
#! /bin/bash
files=($(ls *.txt))
for fname in ${files[@]}
do
echo -ne "$fname:\t"
if [ -r $fname ]; then
echo -ne "READ(Y)\t"
else
echo -ne "READ(N)\
t"
fi
if [ -w $fname ]; then
echo -ne "WRITE(Y)\t"
else
echo -ne "WRITE(N)\t"
fi
if [ -x $fname ]; then
echo "EXECUTE(Y)"
else
echo "EXECUTE(N)"
fi
done
Output:
abcd.txt: READ(Y) WRITE(Y) EXECUTE(N)
durga@durga-VirtualBox:~/scripts$ test.sh
abc.txt: READ(Y) WRITE(Y) EXECUTE(N)
a.txt: READ(Y) WRITE(Y) EXECUTE(N)
b.txt: READ(Y) WRITE(Y) EXECUTE(N)
c.txt: READ(Y) WRITE(Y) EXECUTE(N)
emp.txt: READ(Y) WRITE(Y) EXECUTE(N)
hyd.txt: READ(Y) WRITE(Y) EXECUTE(N)
output.txt: READ(Y) WRITE(Y) EXECUTE(N)
result.txt: READ(Y) WRITE(Y) EXECUTE(N)
z.txt: READ(N) WRITE(N) EXECUTE(N)
Such type of repeated code we have to define inside a block and we can call that block
where ever required. This block of commands is nothing but function.
Advantages of Functions:
1) It reduces length of the code.
2) It improves readability.
3) It improves maintainability.
4) It promotes DRY principle.
DRY Don't Repeat Yourself.
2nd Way:
function_name()
{
commands
}
#defining a function
wish()
{
echo "Hello
Friends... Good
Evening"
}
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Hello Friends... Good Evening
Hello Friends... Good Evening
Hello Friends... Good
Evening
Eg 2:
#! /bin/bash
f1()
{
echo "I am in f1 function"
}
f2()
{
echo "I am in f2 function"
f1
}
f1
f2
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
199 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
Output:
durgasoft@durgasoft:~/scripts$ test.sh
I am in f1 function
I am in f2 function
I am in f1
function
Function
with
Parameter
s:
Function can accept parameters also. With in the function we can access parameters as
follows:
$1 First Parameter
$2 Second Parameter
$@ All Paramters
$* All parameters
$# Total number of parameters
$0 It is script name but not function name
demo 10 20 30 40 50
Output:
First Parameter: 10
Second Parameter: 20 # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
200 DURGASOFT,
Third Parameter: 30 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Total Number of Paramerters: 5 Maii: [email protected]
All Parameters with @: 10 20 30
40 50
UNIX/
LINUX
Eg:
#! /bin/bash
wish()
{
if [ $# -eq 0 ]; then
echo "Hello Guest Good Evening"
else
echo "Hello $1 Good Evening"
fi
}
wish
wish
Durga
wish Sunny
Output:
durgasoft@durgasoft:~/scripts$ test.sh
Hello Guest Good Evening
Hello Durga Good
Evening Hello Sunny
Good Evening
Q3) Write a Function that takes 2 Integer Numbers as
Parameters and perform Arithmetic Operations
#! /bin/bash
calc()
{
if [ $# -ne
2 ]; then
echo "You should pass exactly 2 arguments"
else
a=$1
b=$2
echo
"$a+
$b =
$
((a+
b))"
echo "$a-$b = $((a-b))"
echo "$a*$b = $((a*b))"
echo "$a/$b = $((a/b))"
echo
fi DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
} 201 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
calc 10 Maii: [email protected]
calc 20 10
calc 200 100
UNIX/LINUX
Output:
You should pass exactly 2 arguments
20+10 = 30
20-10 = 10
20*10 = 200
20/10 = 2
200+100 = 300
200-100 = 100
200*100 = 20000
200/100 = 2
2000+1000 = 3000
2000-1000 = 1000
2000*1000 = 2000000
2000/1000 = 2
Output: No parameters
passed to this function
D
UNIX/LINUX
Output:
The Maximum of 10 and 20: 20
The Maximum of 200 and 100 :200
Q6) Write a Function to find Maximum of 3 given Integer
Numbers?
#! /bin/bash
max()
{
a=$1
b=$2
c=$3
if [ $a -gt $b -a $a -gt $c ]; then
echo "Biggest Number:$a"
elif [ $b -gt $c ]; then
echo "Biggest Number:$b"
else
echo "Biggest Number:
$c"
fi
}
read -p "Enter First Number:" n1
read -p "Enter Second Number:" n2
read -p "Enter Third Number:" n3
max $n1 $n2 $n3
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
203 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
Output:
Both Numbers are
equal 10 is less than 20
200 is greater than 100
Q8) Write a Function to find Factorial of a given Integer
Number?
#! /bin/bash
factorial()
{
original=$n
fact=1
while [ $n -gt 1 ]
do
let fact=fact*n
let n--
done
echo "The
Factorial of
$original is:
$fact"
}
read -p "Enter a number to find factorial:" n
factorial $n
}
#! 204
/bin/bash DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
factorial() 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
{
original=$1
x=$1
fact=1
while [ $x -gt 1 ]
do
let fact=fact*x
let x--
done
echo "The
Factorial of
$original is:
$fact"
}
read -p "Enter a number to find factorial:" n
factorial $n
}
durga@durga-VirtualBox:~/scripts$
test.sh The Factorial
The Factorial of 7: 5040of 1: 1
The Factorial of 2: 2
The
205Factorial ofDURGASOFT,
3: 6 # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
The Factorial of 4: 24 Maii: [email protected]
The Factorial of 5: 120
The Factorial of 6: 720
UNIX/
LINUX
The Factorial of 8: 40320
The Factorial of 9: 362880
The Factorial of 10: 3628800
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is Even or
Odd:10 10 is an Even Number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is Even or
Odd:13 13 is an Odd Number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any number to test whether it is positive or negative:10
10 is a Positive Number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any number to test whether it is positive or negative:-
20
-20 is a Negative Number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any number to test whether it is positive or negative:0
It is just Zero
Prime Numbers:
Any positive number greater than 1, which has no other factors except 1 and the number
itself, is called prime number.
Eg: 2, 3, 5, 7, 11, 13 etc
Any Positive Number which has more than 2 factors, such type of numbers are called
Composite Numbers.
Eg: 4, 6, 8, 12 etc
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is PRIME or
not:129 129 is not a PRIME Number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is PRIME or
not:127 127 is a PRIME Number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is PRIME or
not:19 19 is a PRIME Number
durga@durga-VirtualBox:~/script
durga@durga-VirtualBox:~/scripts$
UNIX/
LINUX
Enter n value:2
2
3
durga@durga-VirtualBox:~/scripts$ test.sh
Enter n value:5
2
3
5
7
11
Variable Scope:
Bydefault every variable in shell script is global. i.e we can access anywhere in our script.
But before using a variable, it should be declared already.
Eg 1:
#! /bin/bash
f1()
{
echo "x
value : $x"
}
x=10
f1
Out
put:
x
valu
e:
10
Eg
2:
#! /bin/bash
f1()
{
x=20
echo "x
value : $x"
}
x=10
f1
echo
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
210
"Aft
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
er f1 Maii: [email protected]
exec
utio
nx
UNIX/LINUX
Eg 3:
#! /bin/bash
f1()
{
echo "x
value :
$x"
}
f1
x=10
f1
Out
put:
x
valu
e:
x
valu
e:
10
The variables which are declared inside a function, can be accessed outside of that
function, because every variable has global scope by default.
Eg 4:
#! /bin/bash
f1()
{
x=10
}
f1
echo "x
value : $x"
Output: x
value : 10
If we want a variable only within the function and should not be available outside of that
function, then we have to use local keyword for the variable.
local variables can be accessed only inside function and cannot be accessed outside of that
function.
Eg:
#! /bin/bash
f1()
211 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
{
Maii: [email protected]
local x=10
echo
"Inside
UNIX/LINUX
Ouput:
Inside function x value: 10
outside function x value :
Return
Statement in
Functions:
Every function in shell scripting returns some value. The default returned value is the exit
code of the last command inside function.
But based on our requirement we can return values explicitly by using return statement.
return <exitcode>
The allowed values for exitcode are 0 to 255.
0 means successful
non-zero means unsuccessful.
Eg:
#! /bin/bash
sum()
{
if [ $# != 2
]; then
echo "You should pass exactly two numbers"
return 1
else
echo "The SUM:$(($1+$2))"
fi
}
sum 10 20
echo "The Return value of this function:$?"
echo
sum 10
echo "The Return value of this function:$?"
durgasoft@durgasoft:~/scripts$ test.sh
The SUM:30
The Return value of this function:0
Use Case:
backup()
{
commands to take backup
}
backup
if [ $? != 0 ]; then
something goes wrong backup failed
else
backup successful
fi
break vs exit vs return:
1) break:
We can use break only inside loops to break loop exeuction.we will come out of the
loop and remaining statements after loop will be executed.
2) exit:
We can use anywhere exit statement to terminate script execution.The script will be
terminated. No chance of executing any other statement.
3) return:
We can use return statement only inside function to stop function execution. After
return statement, the remaining statements inside function won't be exeuction. But
after function call the remaining statements will be executed.
test.sh
#! /bin/bash
. ./util.sh #This is just inclusion and we are not executing util.sh
add 10 20
subtract 20 10
multiply 10 20
divide 20 10
echo "The value of x:$x"
echo "The value of y:
$y"
durga@durga-VirtualBox:~/scripts$ test.sh
10 + 20 = 30
20 - 10 = 10
10 * 20 = 200
20 / 10 = 2
The value of x:888
The value of
y:999
Topic-34
Shell Script
Projects
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
215 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX
If the above conditions are satified then user is valid secret agent and share information
about our next operation, otherwise just send thanks message.
durga@durga-VirtualBox:~/scripts$
test.sh
Welcome to DURGASOFT BOOK RENTAL APPLICATION
############################################
Was Book returned before 9 PM [Yes|No]:Yes
How many days was Book Rented:6
What day the Book rented:Saturday
The Cost Of Book Rental: Rs 126.0
Hello, You got Rs 54.0 Discount, Enjoy..
Visit Again...
durga@durga-VirtualBox:~/scripts$
test.sh
Welcome to DURGASOFT BOOK RENTAL APPLICATION
############################################
Was Book returned before 9 PM [Yes|No]:No
How many days was Book Rented:6
What day the Book rented:Monday
The Cost Of Book Rental: Rs 210
Visit Again...
$
l
i
n
e
c
u
t
-
d
" DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
225 : 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
" Maii: [email protected]
-
UNIX/
LINUX
88) record=$line
89) break
90) fi
91) done < users.dat
92) mv temp.dat users.dat
93) read -p "Enter New Password:" npwd
94) uid=$(echo $record | cut -d ":" -f 1)
95) fname=$(echo $record | cut -d ":" -f 3)
96) lname=$(echo $record | cut -d ":" -f 4)
97) zipcode=$(echo $record | cut -d ":" -f 5)
98) echo "$uid:$npwd:$fname:$lname:$zipcode" >> users.dat
99) echo "Password updated successfully"
100) echo
101) echo
102) }
103) delete_user()
104) {
105) read -p "Enter User Id: " uid
106) count=$(cat users.dat | cut -d ":" -f1 | grep -w $uid | wc -l)
107) if [ $count -eq 0 ]; then
108) echo "User Id: $uid does not exist, Cannot Delete User"
109) echo
110) return 3
111) fi
112) read -p "Enter Password: " pwd
113) count=$(cat users.dat | grep -w $uid | cut -d ":" -f 2 | grep -w $pwd |wc -l)
114) if [ $count -eq 0 ]; then
115) echo "Invalid Password, Cannot Delete User"
116) echo
117) return 4
118) fi
119) while read line
120) do
121) fuid=$(echo $line | cut -d ":" -f1)
122) fpwd=$(echo $line | cut -d ":" -f2)
123) if [ $uid = $fuid -a $pwd = $fpwd ]; then
124) grep -v $line users.dat > temp.dat
125) break
126) fi
127) done < users.dat
128) mv temp.dat users.dat
129) echo "User Deleted Successfully"
130) echo
131) echo
132) }
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
226 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
133) show_all_users()
134) {
135) echo "All Users Information:"
136) echo "----------------------"
137) cat users.dat
138) echo
139) echo
140) }
141) users_count()
142) {
143) count=$(cat users.dat | wc -l)
144) echo "The Total Number of users:$count"
145) echo
146) echo
147) }
148) echo "Welcome to User Management Application"
149) echo "######################################"
150) while [ true ]
151) do
152) echo "1. Add User"
153) echo "2. Search For User"
154) echo "3. Change Password"
155) echo "4. Delete User"
156) echo "5. Show All Users"
157) echo "6. Users Count"
158) echo "7. Exit"
159) read -p "Enter Your Choice [1|2|3|4|5|6|7]:" choice
160) case $choice in
161) 1)
162) add_user
163) ;;
164) 2)
165) search_user
166) ;;
167) 3)
168) change_password
169) ;;
170) 4)
171) delete_user
172) ;;
173) 5)
174) show_all_users
175) ;;
176) 6)
177) users_count
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
227 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
178) ;;
179) 7)
180) echo "Thanks for using application"
181) exit 0
182) ;;
183) *)
184) echo "Wrong choice...Try again"
185) esac
186) done
emp.dat eno|ename|esal|eaddr|dept|
gender 100|sunny|1000|mumbai|admin|
female 200|bunny|2000|chennai|sales|
male 300|chinny|3000|delhi|accounting|
female 400|vinny|4000|hyderabad|
admin|male 500|pinny|5000|mumbai|
sales|female
229
4) Display
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
Multiple
Lines in
UNIX/LINUX
Note: We can use cut command to read data column wise, where as we can use sed
command to read row wise data.
After 1d we are using enter key. It will delete first and last records.
1. $sed
's/durga/linux/g'
demo.txt
It will replace all occurrences of durga with linux while displaying the content. It won't
modify file content.
4. $ sed
's/DURGA/linux/g
i' demo.txt
While performing
replacement to
ignore case.
5. $ sed -i
's/DURGA/linux/gi
' demo.txt
To replace
permanently in the
file. This command
won't display
anything to the
console.
7. $ sed -i 's/\
<sunny\>//gi'
demo.txt
It deletes every
occurrence of sunny
in the file. HereDURGASOFT,
case # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
232
won't be considered. 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
BEGIN block will be executed only once before processing the file.
ACTION block will be executed for every line/record present in the file.
END block will be executed only once after completing all lines/records
processing.
Eg: input.txt
Any subject will provide huge benefit.
The useless waste activities we should not do.
Atleast one new activity we should do per day.
Don't Play games with Money.
Action
Action
Action
END
Eg:
awk
comm
and to
print
file
data
and
the
numb
er of
lines
233 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
awk
'BEGI
N{prin
UNIX/
LINUX
c=c+1;
}
END
{
pr
in
t
".
...
...
...
...
...
...
...
...
";
pr
in
t
"
T
h
e
N
u
m
b
er
O
f
Li
n
es
:
"
c
}'
inp
ut.t
xt
dur
gas
oft
@d
urga DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
234
soft 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
:~/ Maii: [email protected]
scri
pts$
UNIX/
LINUX
Note:
1. Normal Bash commands like echo won't work in AWK.
2. $0 represents total line/record.
Q) Can we
restrict on
no of times
action
block
should be
executed?
Yes. We
enocan ename esal eaddr
100define
Sunny 1000 Mumbai
some
200 Bunny 2000 Hyderabad
300constrain
Chinny 3000 Hyderabad
ts. will
400 Vinny be 4000 Chennai
500discussed
Pinny 5000 Mumbai
in next
level
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
235
Process 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
ing
UNIX/LINUX
Instead of tab, if we use any other separator then we can handle by using FS variable or -F
option. Will be discussed in next level
Bydefault tab is separator in awk. Instead of tab if we are using any separator then we
should use either -F option or FS variable. FS is predefined variable in awk.
emp.csv
eno,ename,esal,eaddr
100,Sunny,1000,Mumbai
200,Bunny,2000,Hyderabad
300,Chinny,3000,Hyderabad
400,Vinny,4000,Chennai
500,Pinny,5000,Mumbai
ename eaddr
Sunny Mumbai
Bunny Hyderabad
Chinny Hyderabad
Vinny Chennai
Pinny Mumbai
Display
Table
Content
without
Header:
We can use AWK
prededined variable
NR, which means
Row Number.
What
is the
outpu
t of
the
follow
ing
comm
ands:
1. awk
'{pri
nt
$0;}
'
xy.t
xt
2. awk
'{pri
nt
$1;}
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
'239
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
xy.t Maii: [email protected]
xt
3. awk
UNIX/LINUX
x.txt
BEGIN {print "BEGIN"}
{print $0}
END { print "End"}
x.txt
BEGIN {FS=",";print
"BEGIN"}
{print $0}
END { print "End"}
Display
Records based
on given
Search String:
We have to specify the
search string as follows
/searchstring/
If Total Field
Value needs to
be matched:
awk '/2000/{print $0}' FS="," emp.csv
awk '$3~/2000/{print $0}' FS="," emp.csv
awk '$3==2000{print $0}' FS="," emp.csv
If third field value exactly 2000, then only record will be printed.
awk '$4=="Hyderabad"{print $0}' FS="," emp.csv
If 4th field value exactly Hyderabad, then only record will be
printed.
2nd Way
x.txt
BEGIN{
FS=",";
c=0;
} NR!
=1{
if($3>
3000)
{
c=c+1;
print $0;
}
}
END{
prin
t
"Th
e
Tot
al
Nu
mb
er
of
Em
plo
yee
s
wh
ere
sala
ry >
300
0 :"
eno
c ename esal eaddr
100
} Sunny 1000 Mumbai
200 Bunny 2000 Hyderabad
durga@durga-VirtualBox:~/Desktop$ awk -f x.txt emp.csv
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
243
400,Vinny,4000,Chennai
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
500,Pinny,5000,Mumbai Maii: [email protected]
20,Durga,5000,Hyderabad
2000,Pavan,20000,Hyderabad
UNIX/
LINUX
300 Chinny Hyderabad
3000 Chennai
400 Vinny 4000 Mumbai
500 Pinny 5000
durgasoft@durgasoft:~/scripts$ awk 'NR!=1{if($3>3000){print $2" is very costly
employee"}else{print $2" is not costly employee"}}' emp.txt
Sunny is not costly employee
Bunny is not costly employee
Chinny is not costly employee
Vinny is very costly employee
Pinny is very costly employee
x.txt
BEGIN{
FS=",";
} NR!
=1{
i
f
(
$
3
>
3
0
0
0
)
{
p
r
i
n
t
$
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
244 2 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
" Maii: [email protected]
i
UNIX/LINUX
echo "CAT RAT DOG TIGER" | awk '{for(i=1;i<=NF;i++){print "Field:" i":" $i}}'
cat emp.txt | awk '{for(i=1;i<=NF;i++){print "Field:" i":" $i;}print "";}'
Field:1:100
Field:2:Sunny
Field:3:1000
Field:4:Mumbai
Field:1:200
Field:2:Bunny
Field:3:1000
Field:4:Hyderabad
Field:1:400
Field:2:Vinny
Field:3:4000
Field:4:Chennai
Field:1:500
Field:2:Pinny
Field:3:5000
Field:4:Mumbai
Predefin
ed
Variables
of awk:
FS Field
Separator
NR Row Number / Number of Rows
NF Number of Fields
RS Record Separator
echo "Apple Banana Carrot" | awk 'END{print "The Number of Records:" NR;print "The
Number of Fields:" NF}'
cat emp.txt | awk 'END{print "The Number of Records:" NR;print "The Number of Fields:"
NF}'
awk 'END{print "The Number of Records:" NR;print "The Number of Fields:" NF}' emp.txt
Note: In BEGIN Block, NR and NF representing zero. Hence we cannot use these inside
BEGIN Block.
demo.txt
APPLE,BANANA:CAT,DOG:JAVA,PYTHON
Record Number:2
CAT--->DOG
Record Number:3
JAVA--->PYTHON
Note: We can change order of BEGIN,ACTION and END blocks but not recommended.
durga@durga-VirtualBox:~/Desktop$ awk '{print "ACTION"}BEGIN{print
"BEGIN"}END{print "END"}' demo.txt
o/p:
BEGIN
ACTION
END
----------
----------
----------
----------
----------
----------
-
test.sh -l /etc
test.sh --location /etc -e conf
test.sh --location /etc -e conf -s
test.sh --location /etc -e conf --stats
test.sh -e txt
test.sh
#! /bin/bash
while [ $# != 0 ]
do
case $1 in
-l|--location)
echo "-l |
--location
option
provided
"
LOCATI
ON=$
2
echo "$LOCATION provided as argument"
shift
shift
;; DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
248
-e|--extension) 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
echo "-e | --extension option provided"
EXTENSION=$2
echo "$EXTENSION provided as
UNIX/
LINUX
shift
shift
;;
-s|--stats)
echo "-s|--stats option provided"
shift
;;
-h|--help)
echo "-h|--help option provided"
shift
;;
*)
echo "Invalid Option"
shift
esac
done
Out
put
durga@durga-VirtualBox:~/scripts$ test.sh
durga@durga-VirtualBox:~/scripts$ test.sh -l /etc
-l | --location option provided
/etc provided as argument
durga@durga-VirtualBox:~/scripts$ test.sh -l
/etc --extension txt
-l | --location option provided
/etc provided as argument
-e | --extension option
provided txt provided as
argument
durga@durga-VirtualBox:~/
scripts$ test.sh -e txt -l /etc
-e | --extension option
provided txt provided as
argument
-l | --location option provided
/etc provided as argument
durga@durga-VirtualBox:~/
scripts$ test.sh -e txt -l /etc --
stats
-e | --extension option
provided txt provided as
argument
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
-l 249
| --location option provided
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
/etc provided as argument Maii: [email protected]
-s|--stats option provided
durga@durga-VirtualBox:~/
UNIX/
LINUX
-s|--stats option provided
durga@durga-VirtualBox:~/scripts$ test.sh durga
Invalid Option
durga@durga-VirtualBox:~/scripts$ test.sh durga -l /etc
Invalid Option
-l | --location option provided
/etc provided as argument
Q2) Write a Script to find the Number of Files Present in the given
Location?
test.sh -l /etc
test.sh -l
/bin
test.sh
#! /bin/bash
LOCATION=$
2
if [ ! -d
$LOCATION ];
then
echo "You should provide valid directory as Location"
exit 1
fi
Output
durga@durga-VirtualBox:~/scripts$ test.sh -l /etc
The Number of Files:93
durga@durga-VirtualBox:~/scripts$ test.sh -l /bin
The Number of Files:140
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts
The Number of Files:19
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts/dir99
The Number of Files:0
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts/dir9999
You should provide valid directory as Location
test.sh
#! /bin/bash
LOCATION=$2
EXTENSION=$4
if [ ! -d
$LOCATION ];
then
echo "You should provide valid directory as Location"
exit 1
fi
Output
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts -e txt
The Number of Files:10
durga@durga-VirtualBox:~/scripts$ test.sh -l /etc -e conf
The Number of Files:31
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts/dir99 -e txt
The Number of Files:0
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts -e conf
The Number of Files:0
durga@durga-VirtualBox:~/scripts$ test.sh -l ~/scripts -e sh
The Number of Files:7
Q4) Write a Script to find Total Size of all Files based on given
Location and Extension?
test.sh
#! /bin/bash
LOCATION=$2
EXTENSION=$4
if [ ! -d
$LOCATION ];
then
echo "You should provide valid directory as Location"
exit 1
fi
Q5) Write a Script to find Largest File and Smallest File based on
given Location and Extension?
test.sh
#! /bin/bash
LOCATION=$2
EXTENSION=$4
if [ ! -d
$LOCATION ];
then
echo "You should provide valid directory as Location"
exit 1
fi
|
a
w
k
'
/
^
-
/
'
|
g
r
e
p
"
.
$
E
X
T
E
N
S
I
O
N
$
"
| DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
255
66) a 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
w Maii: [email protected]
k
'
UNIX/
LINUX
106) fi
1) #! /bin/bash
2) help_function() 3)
{
4) echo "$0 can
provide
information
based on
location,exte
nsion
including
memory
info"
5) echo
6) echo "$0 [-l location][--location location][-e extension][--extension
extension][- s|--stats][-h|--help]"
7) echo
8) echo "Examples:"
9) echo "$0 -l /etc"
10) echo "$0 -l /etc -e conf"
11) echo "$0 -l /etc -e conf --stats"
12) exit 2
13) }
14)
15) L
O
C
A
T
I
O
N
=
$
(
p
w
d
)
16) E
256X DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
T
Maii: [email protected]
E
N
S
UNIX/
LINUX
37) STATS=1
38) shift
39) ;;
40) -h|--help)
41) help_function
42) ;;
43) *)
44) echo "You are providing invalid option, please check help doc below"
45) help_function
46)
47) esac
48)done
49)
50) echo
-n
"This
scrip
t
findi
ng
all
files
with
"
51) if
[ "$E
XTE
NSIO
N" =
"" ];
then
52) ech
o-
n
"all
ext
ens
ion
s in
"
53) else
54) ech
o-
n ".
$E
XT
257 EN SIO
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
N
ext
ens
UNIX/
LINUX
82) END{
83) print "The Number of Files:" NR;
84) print "The Total Size of all files: " sum " Bytes";
85) print "The Total Size of all files: " sum/1024 " KB";
86) print "The Total Size of all files: " sum/1024/1024 " MB";
87) print ""
88) }
89)
90) awk_code_2:
91) -----------
92) {
93) if(NR==1){
94) min_file_size=$5;
95) min_file_name=$9;
96) max_file_size=$5;
97) max_file_name=$9;
98) }
99) else{
100) if($5<min_file_size){
101) min_file_size=$5;
102) min_file_name=$9;
103) }
104) if($5>max_file_size){
105) max_file_size=$5;
106) max_file_name=$9;
107) }
108) }
109) }
110) END{
111) print "The Smallest File Name: " min_file_name;
112) print "The Smallest File Size: " min_file_size;
113) print "The Largest File Name: " max_file_name;
114) print "The Largest File Size: " max_file_size;
115) }
Output
durga@durga-VirtualBox:~/scripts$ test.sh -l /etc -e conf -s
This script finding all files with .conf extension in /etc location
durga@durga-VirtualBox:~/
scripts$ ls -l *.txt
-rw-r--r-- 1 durga newgrp 217 Apr
2 19:17 abcd.txt
-rw-r--r-- 1 durga newgrp 16 Apr 9
13:10 abc.txt
-rw-r--r-- 1 durga newgrp 243 Apr
2 19:17 a.txt
-rw-r--r-- 1 durga newgrp 243 Apr
2 19:17 b.txt
-rw-r--r-- 1 durga newgrp 254 Apr
2 19:17 c.txt
-rw-r--r-- 1 durga newgrp 216 Apr
2 20:04 emp.txt
-rw-r--r-- 1 durga newgrp 51 Apr 2
19:41 hyd.txt
-rw-r--r-- 1 durga newgrp 838 Apr
5 20:16 output.txt
-rw-r--r-- 1 durga newgrp 696 Apr
2 20:31 result.txt
----r--r-- 1 durga newgrp 26 Mar
30 11:53 z.txt
durga@durga-VirtualBox:~/
scripts$ test.sh -e txt -s
This script finding all files
with .txt extension in
/home/durga/scripts location
Part-3
Linux
Administration
Basics
Agenda
Topic-38: Job Scheduling with crontab
Topic-49: at command
$ crontab -e
To edit already existing cron jobs and to define new cron jobs.
$ crontab -r
To remove all configured cron jobs.
$ crontab filename
Install a new crontab from file
Format of crontab:
m h dom mon dow command
Q. Write a script that takes backup of our Desktop directory and place that
backup copy inside backup directory present in user home directory?
Configure this script as cron job, which should be executed every FRIDAY
23:59.
test.sh
tar -cjf backup$(date +%d_%m_%Y_%H_%M).tar ~/Desktop/*
mv backup$(date +%d_%m_%Y_%H_%M).tar ~/backup
configure in crontab
# m mo dow command
h *
n FRI bash ~/test.sh
dom 59
23 *
Various Possibilities of specifying Date and Time:
# m h dom mon dow command
1) Every minute * * * * *
2) Every 2 minutes */2 * * * *
*/2 means every 2nd minute
3) Every even minute */2 * * * *
4) Every odd minute 1-59/2 * * * *
1-59 means range from 1 to 59
16)Every Day at 1 AM
01***
20)Only on week-ends
0 0 * * 6,0
21)Every month on 1st
001**
22)Every other month/ Every alternative month/ every 2 months once
0 0 1 */2 *
23)Every 6 months once
0 0 1 */6 *
Crontab Shortcuts:
@yearly 0011*
@annually 0 0 1 1 *
001**
@monthly 0 0 * * 0
@weekly 0 0 * * *
@daily
@midnight 00***
@hourly 0 0-23 * * *
Note: Crontab shortcuts may not be supported by most of the linux flavours.
Note: While creating new user, if we are not specifying groupname, then a new group
will be created with the same name as username.
pyuser2:x:1006:1007:,,,:/home/pyuser2:/bin/bash
syntax: su newuser
durga@durga-VirtualBox:~$ whoami
durga
durga@durga-VirtualBox:~$ su pyuser1
Password:
pyuser1@durga-VirtualBox:/home/
durga$ whoami
pyuser1
pyuser1@durga-VirtualBox:/home/durga$ exit
exit
durga@durga-VirtualBox:~$ whoami
durga
Note: If we use su command without any argument, then it will switch to root user.
Hence the following 2 commands are equal. (But in ubuntu this option is not working)
$ su
$ su root
durga@durga-VirtualBox:~$ whoami
durga
durga@durga-VirtualBox:~$ pwd
/home/durga
durga@durga-VirtualBox:~$ export x=9999
durga@durga-VirtualBox:~$
268 DURGASOFT, # echo
202, 2$x
nd
Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
9999
Maii: [email protected]
UNIX/
LINUX
durga@durga-VirtualBox:~$ su pyuser1
Password:
pyuser1@durga-VirtualBox:/home/durga$ whoami
pyuser1
pyuser1@durga-VirtualBox:/home/durga$ pwd
/home/durga
pyuser1@durga-VirtualBox:/home/durga$ echo $x
9999
If we use - option with su command, then both user and environment will be switched.
durga@durga-VirtualBox:~$ whoami
durga
durga@durga-VirtualBox:~$ pwd
/home/durga
durga@durga-VirtualBox:~$ export x=9999
durga@durga-VirtualBox:~$ echo $x
9999
durga@durga-VirtualBox:~$ su - pyuser1
Password:
pyuser1@durga-VirtualBox:~$ whoami
pyuser1
pyuser1@durga-VirtualBox:~$ pwd
/home/pyuser1
pyuser1@durga-VirtualBox:~$ echo $x
Here x is not available because x is
environment variable of durga user.
sudo apt install finger # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
nd
269 DURGASOFT,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
durga@durga-VirtualBox:~$ sudoMaii:
apt [email protected]
install finger
[sudo] password for durga:
Reading package lists... Done
UNIX/
LINUX
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
fonts-liberation2 fonts-opensymbol
gir1.2-geocodeglib-1.0 gir1.2-gst-plugins-base-1.0
gir1.2-gstreamer-1.0 gir1.2-gudev-1.0
gir1.2-udisks-2.0 grilo-plugins-0.3-base
gstreamer1.0-gtk3 libboost-date-time1.65.1
libboost-filesystem1.65.1 libboost-iostreams1.65.1
libboost-locale1.65.1 libcdr-0.1-1
libclucene-contribs1v5 libclucene-core1v5
libcmis-0.5-5v5 libcolamd2 libdazzle-1.0-0
libe-book-0.1-1 libedataserverui-1.2-2 libeot0
libepubgen-0.1-1 libetonyek-0.1-1 libevent-2.1-6
libexiv2-14 libfreerdp-client2-2 libfreerdp2-2
libgee-0.8-2 libgexiv2-2 libgom-1.0-0 libgpgmepp6
libgpod-common libgpod4 liblangtag-common liblangtag1
liblirc-client0 liblua5.3-0 libmediaart-2.0-0
libmspub-0.1-1 libodfgen-0.1-1 libqqwing2v5 libraw16
librevenge-0.0-0 libsgutils2-2 libssh-4
libsuitesparseconfig5 libvncclient1 libwinpr2-2
libxapian30 libxmlsec1 libxmlsec1-nss lp-solve
media-player-info python3-mako python3-markupsafe
syslinux syslinux-common syslinux-legacy
usb-creator-common
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
finger
0 upgraded, 1 newly installed, 0 to remove and 235 not upgraded.
Need to get 15.6 kB of archives.
After this operation, 48.1 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu bionic/universe amd64 finger amd64 0.17-
15.1 [15.6 kB]
Fetched 15.6 kB in 8s (1,977 B/s)
Selecting previously unselected package finger.
(Reading database ... 119576 files and directories currently installed.)
Preparing to unpack .../finger_0.17-15.1_amd64.deb ...
Unpacking finger (0.17-15.1) ...
Setting up finger (0.17-15.1) ...
Processing triggers for man-db
(2.8.3-2ubuntu0.1) ...
durga@durga-VirtualBox:~$
Login: durga Name: durga
finger durga
Directory: /home/durga Shell: /bin/bash
On since Tue Jan 28 16:56 (IST) on :0 from :0 (messages off)
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
270 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Mail last read Wed Jan 8 20:44 2020 (IST)
No Plan.
durga@durga-VirtualBox:~$ su pyuser2
No passwd entry for user 'pyuser2'
durga@durga-VirtualBox:~$ sudo
delgroup pythongroup
/usr/sbin/delgroup: `pyuser1' still has
`pythongroup' as their primary group!
durga@durga-VirtualBox:~$ ls -l
ddd.txt
-rw-r--r-- 1 root durga 0 Jan 28 17:16 ddd.txt
durga@durga-VirtualBox:~$ sudo chgrp root ddd.txt
durga@durga-VirtualBox:~$ ls -l ddd.txt
-rw-r--r-- 1 root root 0 Jan 28 17:16 ddd.txt
Note: We can find groups associated with particular user by using groups command
as follows
$ groups username
Adduser is not a standard Linux command. It is essentially a Perl script that uses
the useradd command in the background. This high-level utility is more efficient in
properly creating new users on Linux. Default parameters for all new users can also
be set through the adduser command.
We can use sudo command to execute commands as another user, mostly root
user.
Note: If we want to use sudo command for any user other than root then we have
to use -u option.
The following two commands are equal.
$ sudo command
$ sudo -u root command
durgasoft@durgasoft:~$ ls -l /etc/sudoers
-r--r----- 1 root root 755 Jan 18 2018 /etc/sudoers
# User alias
specification # Cmnd
alias specification
# User privilege
specification root
ALL=(ALL:ALL)
ALL
# Members of the
admin group may gain root
privileges
%admin ALL=(ALL)
ALL
# Allow members of
group sudo to execute any
command
%sudo ALL=(ALL:ALL)
ALL
$ sudo -l -u username
It will display allowed commands of provided user by sudo.
durgasoft@durgasoft:~$ sudo -l
Matching Defaults entries for durgasoft on durgasoft:
env_reset, mail_badpass,
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
275 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
Maii: [email protected]
PuTTY is an SSH and telnet client can be used to connect with remote servers.
It is developed originally by Simon Tatham for the Windows platform.
PuTTY is open source software.
By using directly
putty.exe File:
Alternative binary files
64-bit: putty.exe
Requirement
s for
connecting
with Putty:
1) Compulsory our
Linux machine
should has
IPAddress
2) SSH server should
be running on the
linux machine
How to
configureDURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
nd
276
ipaddress for 88 85 25 26Maii:27,[email protected]
72 07 21 24 27/28 | www.durgasoftonline.com
our ubuntu
UNIX/
LINUX
durgasoft@durgasoft:~$ ip -br a
lo UNKNO 127.0.0.1/8 : :1/128
enp0s3 WN UP 192.168.0.172/24 fe80::7e7f:57d0:5640:414e/64
Open Mobaxterm Right click on User sessions New Session SSH provide IP
Address OK
*By 1991 almost GNU project completed except kernel development. Kernel is very
important component which is responible to communicate with hardware, to execute our
commands and allocate system resources.
*In 1991, Linus Torvalds developed Linux kernel as the part of his M.Sc thesis at
University of Helsinki, Finland.
*With his Linux kernel contribution, GNU project was completed and GNU operating
System ready.
uname Command:
We can print system information by using uname command.
We can use -s or --kernel-name option to print the kernel name.
We can use -o or --operating-system option to print the
operating system name.
What ever commands we are using in linux are developed by using C language. The
corresponding source is available in gnu.org website.
durgasoft@durgasoft:~/Downloads$ ls
coreutils-8.31.tar.xz
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
280 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
durgasoft@durgasoft:~/Downloads$ file coreutils-8.31.tar.xz
coreutils-8.31.tar.xz: XZ compressed data
We have to uncompress and extract this tar file.
durgasoft@durgasoft:~/Downloads$ ls
coreutils-8.31 coreutils-8.31.tar.xz
durgasoft@durgasoft:~/Downloads/
coreutils-8.31$ ls
ABOUT-NLS configure.ac m4 tests
aclocal.m4 COPYING maint.mk THANKS
AUTHORS dist-check.mk Makefile.am thanks-gen
bootstrap doc Makefile.in THANKS.in
bootstrap.conf gnulib-tests man THANKS-to-translators
build-aux GNUmakefile NEWS THANKStt.in
cfg.mk init.cfg po TODO
ChangeLog INSTALL README
configure lib src
src directory contains source code of all our core util commands.
int
main (int argc, char **argv)
{
printf("Now onwards in customized way date command will work\
n");
....
}
Now we have to compile this modified c file. For this we required gcc.
gcc is bydefault not available and we have to install manually.
We have to execute configure script. It is responsible to configure gcc as per our system
architecture.
durgasoft@durgasoft:~/Downloads/coreutils-8.31$ ls -l configure
-rwxr-xr-x 1 durgasoft durgasoft 1852444 Mar 11 2019 configure
We required make command which is responsible to compile all c files into .o files.
make command is also helpful to install this updated coreutils package.
We have to install this updated core coreutils package by using make command.
Summary:
1) Listing Processes:
1) $ ps
If we are not passing any argument, then it shows processes related to current
session.
durgasoft@durgasoft:~$ ps
PID TTY TIME CMD
20881 pts/0 00:00:00 bash
20890 pts/0 00:00:00 ps
2) $ ps -e
-e means Everything. It shows all processes.
3) $ ps -ef
It shows full listing of all processes
-f means Full Listing
durgasoft@durgasoft:~$ ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 19:41 ? 00:00:02 /sbin/init splash
root 2 0 0 19:41 ? 00:00:00 [kthreadd]
root 3 2 0 19:41 ? 00:00:00 [rcu_gp]
2) Filtering Processes:
We can filter processes based on UID, PID and
PPID.
1) $ ps -f -u durgasoft
It shows all processes which are running related
user durgasoft
2) $ ps -f -u root
283It showsDURGASOFT,
all processes which are running related Ameerpet, Hyderabad - 500038,
nd
# 202, 2 Floor, HUDA Maitrivanam,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
to root user
Maii: [email protected]
UNIX/LINUX
3) $ ps -f -p 20906
It shows process information related to 20906 process id.
4) $ ps -f --ppid 1266
It shows all process information related to parent process id 1266.
2) $ ps -e --forest
Display proces tree
3) $ pstree
Display processes in a tree format
durgasoft@durgasoft:~$ pstree
systemd─┬─ModemManager───2*[{ModemManager
}]
├─NetworkManager─┬─dhclient
│
└─2*[{NetworkManager}]
├─2*[VBoxClient───VBoxClient]
├─2*[VBoxClient───VBoxClient───{V
BoxClient}]
├─VBoxClient───VBoxClient───2*[{V
BoxClient}]
├─VBoxService───7*[{VBoxService}]
├─accounts-daemon───2*[{accounts-
daemon}]
├─acpid
├─avahi-daemon───avahi-daemon
├─boltd───2*[{boltd}]
├─colord───2*[{colord}]
├─cron
├─cups-browsed───2*[{cups-browsed}]
├─cupsd───2*[dbus]
4) $ top
We can use top command to see processes with consumed resources like memory and
cpu utilization. use 'q' to come out of top command.
5) $ htop
It is similar to top , but output will come in gui style.
We have to install separately.
$ sudo apt install htop
3) Online Communication:
Both sender and receiver should be online.
It is also known as two way communication or synchronous communication.
It is something like phone call.
2) Offline Communication:
Only sender should be online, but receiver need not be online.
It is also known as one way communication or asynchronous communication.
It is something like sms or mail.
How to
disable
Messages:
If the receiver is very busy (like durga sir) and he don't want to receive any messages then
he can block messages by using mesg command.
durgasoft@durgasoft:~$
whoami durgasoft
durgasoft@durgasoft:~$ mesg
is y
durgasoft@durgasoft:~$ write demo1
Hello demo1 i am in Linux class
Still new year but faculty is very
cruel ctrl+d
demo1@durgasoft:~$
whoami demo1
demo1@durgasoft:~$
mesg is y
demo1@durgasoft:~$
Message from durgasoft@durgasoft on pts/1 at 20:14 ...
Hello demo1 i am in Linux class
Still new year but faculty is very
cruel EOF
^C
mesg n Option:
demo1@durgasoft:~$
whoami demo1
demo1@durgasoft:~$ mesg n
demo1@durgasoft:~$
mesg is n
durgasoft@durgasoft:~$
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
288
whoami durgasoft 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
durgasoft@durgasoft:~$ write Maii: [email protected]
demo1
UNIX/
LINUX
write: demo1 has messages disabled
demo1 User:
Broadcast message from durgasoft@durgasoft (pts/1) (Wed Jan 1 20:25:52 2020):
mail Command:
mail command is available in mailutils package. Hence we have to install this package if it
is not available.
Regards
Durga
EOT
ctrl+d
durga2
@durga
-
VirtualB
>O 1 durga Fri Jan 3 18:29 17/607 Hello Friends
ox:~$
O 2 durga Fri Jan 3 18:30 17/596 Greetings
mail
?
Heirloom mailx version 12.5 6/20/10. Type ? for help.
"/var/mail/durga2": 2 messages
Held 2 messages in /var/mail/durga2
msmtp is an SMTP client that can be used to send mails from Mutt and probably other
MUAs (mail user agents). It forwards mails to an SMTP server (for example at a free mail
provider), which takes care of the final delivery.
Now is the time to configure msmtp by telling it our gmail credentials, the port to use, the
host, and some other authorization and connection details:
$ gedit ~/.msmtprc
Then, copy the following code in the empty file:
#Gmail account
defaults
#change the location of the log file to any desired location.
logfile ~/msmtp.log
account gmail
auth on
host
smtp.gmail.co
m
from
[email protected] auth
on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
user [email protected]
password unix1234
port 587
#set gmail as your default mail server.
# 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
290 defaultDURGASOFT,
account : gmail
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Saving your password in text format is any of your files is never a good idea. So, you can
secure the file by running the following command: $ chmod 600 .msmtprc
At this point, we have configured our computer to talk to the remote Gmail server. What
we need to do now is, set up a command-line interface that will let us compose emails to
be sent. Mailx is the program that will let us do all this, and here is how we can install it:
Note:
Important: If you are not able to find the package in your already added repositories,
open the sources.list file as follows:
$ nano /etc/apt/sources.list
Then, add the following line to add the rusty-security main universe repository from
where we will install the mailx utility.
Also, do not forget to run the following command before performing the
installation:
$ nano ~/.mailrc
Then, add the following lines in that file and save it.
set sendmail="/usr/bin/msmtp"
set message-sendmail-extra-arguments="-a gmail"
We are now ready to send an email through our configured gmail account to a receiver on
any domain. Following is the basic syntax for sending such an email:
Authenticate as admin
The EOT at the end of the output will indicate that your email has been sent.
However, you might encounter the most common error, same as I did:
This error is mostly encountered when you have not allowed access to less secure apps on
your gmail. This security setting can be changed through the following link:
https://myaccount.google.com/lesssecureapps
When you do so, a notification will be sent to you (mostly on your phone, when you have
configured your phone number with gmail). When you permit this change of setting, gmail
will allow access to less secure apps such as the one we are using.
Package Manager:
It is responsible to installs, upgrades and removes packages.
It is responsible to manage dependencies.
It will track all installed packages.
Eg: yum is the package manager in RedHat Linux.
apt is the package manager in ubuntu.
3) cowsay Command:
An ASCII cow will be displayed in the terminal, which can tell whatever we want.
4) xcowsay Command:
xcowsay is a graphical program and its response is similar to cowsay but in a graphical
manner.
5) yes Command:
It is responsible to generate specified response keep on.
This command mostly used by system administrators to generate some data for
testing purposes.
6) aafire Command:
To display fire in the terminal we can use aafire command. Press any key to
interrupt.
7) figlet Command:
The figlet command can be used to draw large sized text banners.
8) toilet Command:
The toilet command is similar to figlet command and it can be used to draw large sized
text banners by using smaller characters
9) fortune Command:
The fortune command will put up a random fortune message.
$ fortune -s
Once the package installer has finished, we can check to see if the MySQL service is
running.
4. Configure Security
We have to run mysql_secure_installation to configure
security for your MySQL server.
$ sudo mysql_secure_installation
New password:
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.
... skipping.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
... skipping.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.
All done!
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights
reserved.
298 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names
may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> exit
Bye
In MySQL, everything we have to work with our own databases, which are also known as
logical databases.
information_schema
mydb
mysql
performance_schema
sys
Here only one physical database but 5 logical databases are available.
5. To create a table
mysql>create table employees(eno int(5) primary key,ename varchar(20),esal
double(10,2),eaddr varchar(20));
7. To insert data
mysql> insert into employees values(100,'durga',1000,'Hyd');
mysql> insert into employees values(200,'sunny',2000,'Mumbai');
mysql> insert into employees values(300,'bunny',3000,'Hyd');
mysql> insert into employees values(400,'chinny',4000,'Hyd');
Eg:
$ mysql -u root -pDurga@123 -Ddurgadb -e "select * from employees"
DB_USER='root'
DB_PASSWD='Durga@123'
DB_NAME='durgadb'
durga@durga-VirtualBox:~/scripts$
test.sh
+
| -100
- - - - |+ -durga
- - - - - - - +| - -1000.00
- - - - - - - | Hyd |
+
| -200
- - - - |- - -sunny
+ | 2000.00 | Mumbai |
| eno
300 | bunny ename | 3000.00 esal || Hyd |
eaddr
| 400 | chinny | | 4000.00 | Hyd |
+-----+--------+---------+--------+
+--------+
Shell Script to Read Data from User dynamically and
Insert into the Database:
#! /bin/bash
#Declaring mysql DB connection
DB_USER='root'
DB_PASSWD='Durga@123'
DB_NAME='durgadb'
while [ true ]
do
read -p "Employee Number: " eno
read -p "Employee Name: " ename
durga@durga-VirtualBox:~/scripts$
test.sh Employee Number: 500
Employee Name: Dhoni
Employee Salary: 5000
Employee Address: Ranchi
Employee Record
Inserted Successfully
Do you want to insert one more record [Yes|
No]: y Employee Number: 600
Employee Name:
Kohli Employee Salary:
6000 Employee Address:
Delhi
Employee Record
Inserted Successfully
Do you want to insert
one more record [Yes|
No]: NO
durga@durga-VirtualBox:~$ javac
Note: In the old versions we have to set PATH explicitly. But in the newer versions we are
not required to set.
After installation we have to set PATH, then only java related commands will work.
All java related commands are available in the following location:
/usr/lib/jvm/java-8-openjdk-amd64/bin
durga@durga-VirtualBox:/usr/lib/jvm/java-8-openjdk-amd64/bin$
clhsdb javadoc jinfo j s ta t d schemagen
lextcheck
s javah jjs keytool serialver
hsdb javap jmap native2ascii servertool
idlj java-rmi.cgi jps orbd tnameserv
jar jcmd jrunscript pack200 unpack200
jarsigner jdb jsadebugd rmic wsgen
java jdeps jstack rmid wsimport
javac jhat jstat rmiregistry xjc
We have to add this location to the PATH variable then only these commands will be
available to ubuntu.
export PATH=$PATH:/usr/lib/jvm/java-8-openjdk-amd64/bin
$javac Test.java
$ java Test
Java From Ubuntu
1) Foreground Jobs
2) Backgroup Jobs
test.sh
#! /bin/bash
while [ true ]
do
echo "Inside while loop"
sleep 1
done
durga@durga-VirtualBox:~/scripts$ test.sh
Inside while loop
Inside while loop
Inside while
loop
306 Inside DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
while loop Maii: [email protected]
UNIX/
LINUX
Inside while loop
Inside while
loop Inside
while loop
Inside while loop
Inside while
loop Inside
while loop
Inside while loop
^C
durga@durga-VirtualBox:~/scripts$ test.sh
Inside while loop
Inside while loop
Inside while loop
Inside while
loop Inside
while loop
Inside while loop
Inside while
loop
^Z
[1]+ Stopped test.sh
durga@durga-VirtualBox:~/scripts$ fg
test.sh
Inside while loop
Inside while loop
Inside while
loop Inside
while loop
Inside while loop
Inside while
loop Inside
while loop
Inside while loop
Inside while
loop Inside
while loop
Inside while loop
^C
How to Kill
Background
Job:
$ kill -9 pid
How
307to List DURGASOFT,
nd
# 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
all Maii: [email protected]
Background
UNIX/LINUX
Note: In the foreground only one can be executed, but in the background multiple jobs
can be executed.
durga@durga-VirtualBox:~/scripts$ ls
demo.sh env.sh nohup.out Test.class Test.java test.py test.sh
durga@durga-VirtualBox:~/scripts$ cat nohup.out
Inside while loop
Inside while
loop Inside
while loop
Even the user exited or switched to some other user still this nohup job will continue its
execution.
Topic-49: at Command
It executes the given job only once, but at specified time.
durga@durga-VirtualBox:~/scripts$ at now
Eg 1:
durga@durga-VirtualBox:~$ at now
warning: commands will be executed using /bin/sh
at> ls
at> date
at> cal
at> ctrl+d
It executes all commands immediately and writes output into user's mailbox.
Eg 2:
durga@durga-VirtualBox:~$ at now + 2 minutes
warning: commands will be executed using /bin/sh
at> ls > abcd.txt
at> ctrl+d
job 7 at Wed Jan 8 21:08:00 2020
Eg 3:
durga@durga-VirtualBox:~$ at now + 2 Hours
warning: commands will be executed using /bin/sh
at> test.sh > a.txt
at> ctrl+d
Note:
$ at now + 3 days It will be executed after 3 days
$ at now + 1 month It will be executed after 1
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
310
month 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
$ at 3PM tomorrow It will be executed tomorrow at 3PM
$ at 12:30am aug 01 It will be executed at 1st august 12:30 AM.
durga@durga-VirtualBox:~$ atq
8 Wed Jan 8 21:46:00 2020 a durga
9 Wed Jan 8 21:57:00 2020 a durga
batch
Comman
d:
The batch
jobs will be
executed
when ever
server is
free or
server load
is less.
durga@durg
a-
VirtualBox:~
$ batch DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
311
warning: commands will
be 88
executed
85 25 26using
27, 72/bin/sh
07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
at> ls
at> date
at> cal
UNIX/
LINUX
Topic-50: Memory related Commands
1) df Command:
df means disk fragmentation.
It displays file system disk space usage.It provides information about the space available
on all currently mounted file systems.
durga@durga-VirtualBox:~$ df
Filesystem 1K-blocks Used Available Use Mounted on
%
udev 1404040 0 1404040 0% /dev
tmpfs 285584 1584 284000 1% /run
/dev/sda1 10253588 551280 4200216 57% /
4
tmpfs 1427912 0 1427912 0% /dev/shm
tmpfs 5120 4 5116 1% /run/lock
tmpfs
We 1427912
can use multiple options 0
with df command. 1427912 0% /sys/fs/cgroup
-h Human Readable Format
-m In Mega Bytes
-k In Kilo Bytes (It is Default)
durga@durga-VirtualBox:~$ df -m
Filesystem 1M-blocks Used Available Use Mounted on
%
udev 1372 0 1372 0% /dev
tmpfs 279 2 278 1% /run
/dev/sda1 10014 5384 4102 57% /
tmpfs 1395 0 1395 0% /dev/shm
tmpfs 5 1 5 1% /run/lock
durga@durga-VirtualBox:~$ df -h
Filesystem Size Used Avail Use% Mounted on
udev 1.4G 1.4G 0% /dev
tmpfs 0 278M 1% /run
/dev/sda1 279M 1.6M 4.1G 57% /
tmpfs 9.8G 5.3G 1.4G 0% /dev/shm
tmpfs 5.0M 4.0K 5.0M 1% /run/lock
1.4G
tmpfs 01.4G 0 1.4G 0% /sys/fs/cgroup
/dev/loop1 43M 43M 0 100 /snap/gtk-common-themes/1313
%
2) du Command:
du - estimate file space usage
It displays directory wise disk usage in the form of blocks. Each block is 1024 bytes.
durga@durga-VirtualBox:~$ du
4 ./dir10
4 ./Downloads/java/corejava
8 ./Downloads/java
12 ./Downloads
du: cannot read directory ' . / . d b u s ' : Permission denied
4 ./.dbus
4 . / . c o n f i g / u p d a t e -n o t i f i e r
8 ./.config/gedit
12 ./.config/ibus/bus
durga@durga-VirtualBox:~$ du -k
4 ./dir10
4 ./Downloads/java/corejava
8 ./Downloads/java
12 ./Downloads
du: cannot read directory './.dbus': Permission denied
4 ./.dbus
4 ./.config/update-notifier
8 ./.config/gedit
12 ./.config/ibus/bus
16 ./.config/ibus
4 ./.config/enchant
84 ./.config/pulse
4 ./.config/goa-1.0
8 ./.config/gtk-3.0
8 ./.config/evolution/sources
12 ./.config/evolution
durga@durga-VirtualBox:~$ du -h
4.0K ./dir10
4.0K ./Downloads/java/corejava
8.0K ./Downloads/java
12K ./Downloads
du: cannot read directory './.dbus': Permission denied
4.0K ./.dbus
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
313 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/
LINUX
4.0K ./.config/update-notifier
8.0K ./.config/gedit
12K ./.config/ibus/
bus 16K
./.config/ibus 4.0K
./.config/enchant
84K ./.config/pulse
4.0K ./.config/goa-1.0
8.0K ./.config/gtk-3.0
8.0K ./.config/evolution/sources
12K ./.config/evolution
4.0K ./.config/gnome-session/saved-session
8.0K ./.config/gnome-session
28K ./.config/nautilus
20K ./.config/
dconf 212K
./.config
16K ./output5
260K ./.cache/mozilla/firefox/z901vq89.default-release/OfflineCache
12M ./.cache/mozilla/firefox/z901vq89.default-release/startupCache
1 ./dir10
durga@durga-VirtualBox:~$
1 du -m
./Downloads/java/corejava
1 ./Downloads/java
1 ./Downloads
Note: By default du command will always display disk information only about directories.
If we want to get files information also then we have to use -a option.
-a means all
Note: We can use -c option with du command to find grand total disk space.
durga@durga-VirtualBox:~$ du -a -h -c
0 ./dir10/c.txt
0 ./dir10/d.txt
0 ./dir10/a.txt
0 ./dir10/
b.txt 4.0K
./dir10
8.0K
./.ICEauthority
total
.......
3)
40M
free Command:
It displays amount of free and used memory in the system.
durga@durga-VirtualBox:~$ free
total used free shared buff/cache available
Mem: 2855828 1205468 646652 51552 1003708 1434376
Swap: 483800 0 483800
durga@durga-VirtualBox:~$ free - k
total used free shared buff/cache available
Mem: 2855828 1205112 646888 51556 1003828 1434716
Swap: 483800 0 483800
durga@durga-VirtualBox:~$ free -h
total used free shared buff/cache available
Mem: 2.7G 1.1G 631M 50M 980M 1.4G
Swap: 472M 0B 472M
durga@durga-VirtualBox:~$ free -m
total used free shared buff/cache available
Mem: 2788 1176 631 50 980 1401
Swap: 472 0 472
-t, --total
Display a line showing the column totals.
durga@durga-VirtualBox:~$ free - l
total used free shared buff/cache available
Mem: 2855828 1205100 646660 51552 1004068 1434736
Low: 2855828 2209168 646660
High: 0 0 0
Swap: 483800 0 483800
Syntax:
telnet ipaddress
login:XXXX
password:XXXX
Note: telnet is not recommended to use because it is very less secure. Instead of telnet
the people are using ssh(Secure Shell), which is more secured. SSH is applicable only for
*UX Systems (like Linux, UNIX etc).
putty,mobaxterm, xshell can be used to connect with remote servers by using ssh.
By default ssh server is running on ubuntu.
After installation, bydefault ftp server won't run. We have to start manually.
By default, we can download(get) files from remote server. But we cannot upload(put).
To enable upload operation we have to edit the following file:
/etc/vsftpd.conf
ftp Commands:
ftp>ls It display server side
files ftp>!ls It display client side
files
ftp>pwd It display server side present working
directory. ftp>!pwd It display client side present working
directory.
ftp>cd dirname To change to the specified directory on server
machine. ftp>lcd dirname To change to the specified directory on client
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
318
machine. ftp>get filename 88To
85download
25 26 27, 72a07
file
21from the |server.
24 27/28 www.durgasoftonline.com
ftp>mget file1 file2 file3 To download multiple files from the server.
Maii: [email protected]
ftp>mget * To download all files of current working directory from the server.
ftp>mget *.log To download all log files of current working directory from
UNIX/
LINUX
ftp>put filename To upload file to the server.
ftp>mput file1 file2 file3 To upload multiple files to the server.
ftp>? To list all ftp commands
ftp>bye To quit from ftp
ftp>hash To on/off hash. If it is on then it will be off and if it is off then it will be on.
If it is on, then it shows status of download and upload.
Even we can get terminal, to execute some commands on the linux system.
durga@durga-VirtualBox:~$ ps - e f | head - 5
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 21:06 ? 00:00:01 / s b i n / i n i t splash
root 2 0 0 21:06 ? 00:00:00 [kthreadd]
root 3 2 0 21:06 ? 00:00:00 [rcu_gp]
root 4 2 0 21:06 ? 00:00:00 [rcu_par_gp]
Note:
$ init 0 To shutdown the system
$ init 6 To reboot the system
durga@durga-VirtualBox:~$ uname
Linux
durga@durga-VirtualBox:~$ uname
-v
#24~18.04.1-Ubuntu SMP Mon Jul
29 16:12:28 UTC 2019
durga@durga-VirtualBox:~$ uname
-a
Linux durga-VirtualBox 5.0.0-23-generic #24~18.04.1-Ubuntu SMP Mon
Jul 29 16:12:28 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
durga@durga-VirtualBox:~$ df
Filesystem 1K-blocks Used Available Use Mounted on
%
udev 1404164 0 1404164 0% /dev
tmpfs 285608 1580 284028 1% /run
/dev/sda1 10253588 615863 3554384 64% /
6
tmpfs 1428040 0 1428040 0% /dev/shm
tmpfs 5120 4 5116 1% /run/lock
tmpfs 1428040 0 1428040 0% /sys/fs/cgroup
/dev/loop0 90624 90624 0 100 /snap/core/7270
Q4) How to manage services in our system?
%
By using either service or systemctl.
Most of the users don't have root access. Hence they cannot copy new files in our
directory. No chance of spreading viruses.
All linux activities are recorded in log files.
Iptables to manage incoming and outgoing traffic.
327
Both DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
can be used to view large files page by page.
88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
BY using more we can move only in forward direction. But by using less we can move
Maii: [email protected]
either in the forward direction or in the backward direction.
UNIX/LINUX