0% found this document useful (0 votes)
155 views197 pages

Linux Level1

Uploaded by

trishaankkumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views197 pages

Linux Level1

Uploaded by

trishaankkumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 197

UNIX/LINUX

Linux with Shell


Programming,
SED, AWK And
Many More

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

INDEX
Part-1: UNIX/LINUX Concepts & Commands …………………………………………………………………… 4

Topic-1: Overview of UNIX/Linux Operating System ………………………………………………………. 6


Topic-2: Linux File System ……………………………………………………………………………………..……… 10
Topic-3: Linux Installation …………………………………………………………………………………………….. 16
Topic-4: ls,date and cal commands ………………………………………………………………………………. 18
Topic-5: Working with Directories ………………………………………………………………………………… 24
Topic-6: Working with Files …………………………………………………………………………………..……… 34
Topic-8: Comparing Files ………………………………………………………………………………………………. 44
Topic-9: Creation of Link Files ………………………………………………………………………………………. 48
Topic-10: Word count command (wc command) ………………………………………………………….. 51
Topic-11: Sorting content of the file …………………………………………………………………………….. 53
Topic-12: Find unique content in the file by using uniq command ………………………………… 58
Topic-13: Input and Output of Commands and Redirection ………………………………………….. 60
Topic-14: Piping ……………………………………………………………………………………………………………. 65
Topic-15: How to use multiple commands in a single line ……………………………………………… 69
Topic-16: Regular Expressions and Wildcard Characters ……………………………………………….. 70
Topic-17: Command Aliasing ………………………………………………………………………………………… 74
Topic-18: Locate and Find Commands …………………………………………………………………………… 77
Topic-19: Compression and Uncompression of files(tar,gzip,gunzip,bzip2,bunzip2) ………. 85
Topic-20: grep command ……………………………………………………………………………………………… 88
Topic-21: Cut, Paste and tr Commands ……………………………………………………………………….. 102
Topic-22: File Permissions …………………………………………………………………………………………… 106
Topic-23: Working with editors …………………………………………………………………………………… 118

Part-2: Shell Scripting / Shell Programming ………………………………………………………………. 123

Topic-24: Shell Scripting / Shell Programming ………………………………………………………..…… 125


Topic-25: What is shell script, Sha-Bang and First Script ……………………………………………… 128
Topic-26: Shell Variables …………………………………………………………………………………………….. 132
Topic-27: Variable Substitution and Command Substitution ……………………………………….. 136
Topic-28: Command Line Arguments ………………………………………………………………………….. 139
Topic-29: How to read dynamic data from the user ……………………………………………………. 142
Topic-30: Operators ……………………………………………………………………………………………………. 147
Topic-31: Control Statements ……………………………………………………………………………………… 151
Topic-32: Arrays …………………………………………………………………………………………………………. 191
Topic-33: Shell Script Functions ………………………………………………………………………………….. 198

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
2  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-34: Shell Script Projects ……………….…………………………………………………………………… 215


 Project 1: Secret Agent Application ………………………………………………………………… 216
 Project 2: Book Rental Application …………………………………………………………………… 219
 Project-3: Book Management Application ……………………………………………………… 222
 Project-4: User Management Application ………………………………………………………. 224

Topic-35: Stream Editor (SED) …………………………………………………………………………………… 229


Topic-36: AWK Programming ……………………………………………………………………………………. 233
Topic-37: Project on awk programming ……………………………………………………………………… 248

Part-3: Linux Administration Basics …………………………………………………………………………… 260

Topic-38: Job Scheduling with crontab ………………………………………………………………………. 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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Part-1
UNIX / LINUX
Concepts
&
Commands
nd
DURGASOFT, # 202, 2 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-2: Linux File System

Topic-3: Linux Installation

Topic-4: ls, date and cal commands

Topic-5: Working with Directories

Topic-6: Working with Files

Topic-7: Comparing Files

Topic-8: Creation of Link Files

Topic-9: Word count command (wc command)

Topic-10: Sorting content of the file

Topic-11: Find unique content in the file by using uniq command

Topic-12: Input and Output of Commands and Redirection

Topic-13: Piping

Topic-14: How to use multiple commands in a single line

Topic-15: Regular Expressions and Wildcard Characters

Topic-16: Command Aliasing

Topic-17: Locate and Find Commands

Topic-18: Compression and Uncompression of files (tar, gzip, gunzip, bzip2, bunzip2)

Topic-19: grep command

Topic-20: cut command

Topic-21: File Permissions

Topic-22: Working with editors

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5  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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
6  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

All these flavours have lot of similarity. Hence if we are perfect with one flavour, we can
work on any other flavour very easily.

Note: We can view a detailed list of Linux flavours in www.distrowatch.com

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Command Execution Flow

1) User types the command in the terminal.


touch durga.txt
2) Shell reads that command. It will check whether that command is valid or not and
whether it is used properly or not. If everything is proper, then shell
interprets/translates that command into kernal understandable form.
3) Shell handovers that interpreted command to the kernal.
4) Kernal executes that command and perform required activity.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
8  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

5) Once command execution completed, then shell returns unix prompt ($ OR # OR %).
6) $ OR # OR % represents it is ready for the next command.

Online UNIX Terminal:


http://www.masswerk.at/jsuix

✽ It is free terminal and written in JavaScript.


✽ We can access by using any browser.
✽ We can use this terminal to check very basic commands functionality.

The Most commonly used Basic Commands:


1) pwd  Print working directory
2) ls  List our all files and directories
3) mkdir  Create directory
4) cd  Change directory
5) touch  To create a file
6) rmdir  Remove directory
7) rm  To remove file
8) cal  Display Monthly Calander
9) date  Display current date and time.
10) help  To display list of commands.
11) hello  To display brief system information.
12) clear  To clear terminal.
13) exit  To logout session.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-2: Linux
File System
Types of Files in Linux:
In Linux everything is treated as File.
All files are divided into 3 types

1) Normal or Ordinary files:


These files contain data. It can be either text files (like abc.txt) OR binary files (like
images, videos etc).

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: short-cut commands to open and close terminal

ctrl+alt+t  To open terminal


ctrl+d  To close terminal

How to check File Type:


In Ubuntu, blue color files represents directories and all remaining are considered as
normal files. This color conventions are varied from flavour to flavour. Hence it is not
standard way to check file type.

We have to use 'ls -l' command.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
10  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

drwxr-xr-x 102 durgasoft durgasoft 4096 Nov 17 21:19 magic


-rw-r--r-- 1 durgasoft durgasoft 0 Nov 17 21:24 sunny.txt

The first character represents the type of file.


d  Directory File
-  Normal File
l  Link File
c  Character Special File
b  Block Special File
s  Socket File

Note: c, b, s are representing system files and mostly used by super user (also known as
root user or admin user)

File System Navigation Commands:


1) Every directory implicitly contains 2 directories . and ..
. Represents Current Directory
.. Represents Parent Directory

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
nd
DURGASOFT, # 202, 2 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

Linux File System Hierarchy:


Linux file system has Tree Like Structure.
It starts with root(/).
/ is the topmost directory
This root directory contains the following important sub directories.
bin,sbin,lib,etc,dev,opt,home,usr,tmp,media etc

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

Q1) What is the difference between bin and sbin?


bin contains binary executables related to commands used by normal user.
sbin contains binary executables related to commands used by superuser.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
12  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q2) What is the difference between mnt and media?


mnt  Contains manual mounting files.
media  Contains automatic mounting files.

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.

10) var Directory:


 var means variable data. If any data which is keep on changing, such type of data will
be stored inside var directory.
 log files will be stored inside var.

11) home Directory:


 As linux is multi user operating system, for every user a separate directory will be
created to hold his specific data like videos, images, documents etc. All these user
directories will be stored inside home directory.
 $ ls /home
 demo demo1 demo2 durga durga1 durga2 durga5 durgasoft

Note:
/home/durgasoft  Is called durgasoft user home directory. It contains multiple sub
directories like Desktop, Downloads, Movies, Pictures etc.

12) proc Directory:


 proc means processes.
 In Linux, multiple processes are running simultaneously. For every process a unique id
will be there, which is also known as PID (Process ID).
 The data related to current running processes will be stored inside proc directory. For
every process a separate directory will be created inside proc to maintain that
data.The name od this directory is same as PID.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
14  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: We can find all running proceses information by using ps command.


ps means process status.

durgasoft@durgasoft:/$ ps -ef
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
....

13) root Directory:


It is the home directory of super user.

Note:
/home/durgasoft  Durgasoft User Home Directory
/root  Super User Home Directory

Q3) What is the difference between / and Root Directories?


/ acts as root for Linux file system. It is the topmost directory of linux file system.
root is subdirectory of /, which acts as home directory for the super user.

14) boot Directory:


This directory contains the files which are required to boot linux os.

15) usr Directory:


usr means user. This directory contains all user related softwares.

Note:
1) The main advantage of Linux File System is, operating system can locate required files
very easily.
2) For every File System, a separate name will be assigned.
3) ext2,ext3,ext4,XFS are names of Linux File Systems.
4) NTFS, FAT are names of Windows File Systems.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
15  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-3: Linux
Installation
1) Oracle Virtual Box Installation
2) Virtual Machine Installation with Ubuntu OS

1) Oracle Virtual Box Installation:


To run virtual computers in our system without effecting original computer, we should go
for virtual box.
It can extends the capability of our existing computer so that we can run multiple
operating systems simultaneously.

Donwload virtual box from:


virtualbox.org  Downloads  Windows hosts
VirtualBox-6.0.14-133895-Win.exe

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
16  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

2) Creation of Virtual Machine with Ubuntu OS:


We have to download ubuntu software from
ubuntu.com  Download  Ubuntu Desktop  Ubuntu 18.04.3 LTS  Download
ubuntu-18.04.3-desktop-amd64.iso

Note: Download softwares from: bit.ly/36evx8y

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
17  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-4: ls, date and


cal Commands
1) ls Command:
We can use ls command to listout all files and directories present in the given directory.
We can get manual documentation for any command by using man.

man ls
It provides complete information about ls command.

Various options of ls Command:


1) ls
It will display all files and directories according to alphabetical order of names.

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
18  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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:~$ ls -a
. msmtp.log
.. .msmtprc
.bash_history Music
.bash_logout .mysql_history
.bashrc Pictures
.cache .profile
.config Public
.dbus script1.sh
durga@durga-VirtualBox:~$ la -A
.bash_history .msmtprc
.bash_logout Music
.bashrc .mysql_history
.cache Pictures
.config .profile
.dbus Public
nd
DURGASOFT, # 202, 2 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.

 The following are various file attributes


1) The size of the file
2) The number of links
3) The owner
4) The group
5) The creation time
6) The last modified time
7) The last accessed time
etc

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 sub directory contents.

14) ls -s
The number of blocks used by file will be displayed.
1 Block = 1Kb
Note: In ubuntu each block is of 1KB but not 4KB.

15) ls -h
display in human readable format

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: If the number of files are very huge, then we can use less and more commands
with ls to display page by page.

$ 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.

$ ls /dev | head -5  disply only top 5 lines


$ ls /dev | tail -5  display only bottom 5 lines

Note: We can use these options simultaneously. When ever using options simultaneosuly
then the order is not important.

Eg: All the following commands are equal


$ ls -l -t -r
$ ls -t -r -l
$ ls -l -r -t
$ ls -ltr
$ ls -trl

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q4) Is -r will List the Files sorted by Modification Date (Oldest First)?
False.
It lists the files based on reverse of alphabetical order of names.
ls –rt  It will list the files sorted by modification date (Oldest first)

Q5) ls -la will not produce the Same Result as ls -al


False

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
22  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg 1: To display current system date in dd-mm-yyyy format.


default format: mm/dd/yy
date +%d-%m-%Y

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-5: Working with


Directories
1) Creation of Directories:
We can create directories by using mkdir command.

1) mkdir dir1
To create a directory

2) mkdir dir1 dir2 dir3


To create multiple directories

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.

Case Study-1: Film Heroine's Manager


heroines
sunny
jan2020,feb2020,mar2020,......dec2022
katrina
jan2020,feb2020,mar2020,......dec2022
kareena
jan2020,feb2020,mar2020,......dec2022

jan2020
schedule_1.txt
schedule_2.txt
...
schedule_31.txt

$ mkdir heroines
$ cd heroines
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
24  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.

2) How to remove Directories:


We can remove directories by using rmdir command.
1) $ rmdir dir1
To remove empty directory dir1

2) 2. $ rmdir dir1 dir2 dir3


To remove multiple empty directories

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.

durga@durga-VirtualBox:~$ rmdir heroines/


rmdir: failed to remove 'heroines/': Directory not empty

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

$ rm -r heroines
$ rm -R heroines

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 /

Various options with rm Command:


1) interactive Option(-i)
While removing files and directories, if we want confirmation then we have to use -i
option.

durga@durga-VirtualBox:~$ rm -ri dir7


rm: descend into directory 'dir7'? y
rm: remove regular empty file 'dir7/c.txt'? y
rm: remove regular empty file 'dir7/d.txt'? y
rm: remove regular empty file 'dir7/a.txt'? y
rm: remove regular empty file 'dir7/b.txt'? y
rm: remove directory 'dir7'? y

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:~$

Even dir99 is not available, we won't get any error message, because we used -f option.

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'
removed 'dir8/a.txt'
removed 'dir8/b.txt'
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

removed directory 'dir8'


durga@durga-VirtualBox:~$

Q1) What is the difference between the following 2 Commands?


$ mkdir dir1/dir2/dir3
$ mkdir -p dir1/dir2/dir3

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.

Q2) What is the Advanatage of using rm Command over rmdir Command


while removing Directories?
rmdir command will work only for empty directories.
rm command will work for both empty and non-empty directories. Even we can rm
command for files also.

Q3) Assume that dir1 is an Empty Directory. Which of the following


Commands will remove dir1?
 rm dir1
 remove dir1
 rmdir dir1
 del dir1

 Ans: C

Q4) Assume that dir1 is non-empty Directory. Which of the following


Commands will remove dir1?
 rmdir dir1
 rm -R dir1
 rm -i dir1
 rm -f dir1
 rm -v dir1

 Ans: B

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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

Q6) How to Create a Directory called pythonclasses in the Videos Directory


within User Home Directory?
$ mkdir ~/Videos/pythonclasses

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

Q9) To Create a Directory named with Java Classes, is the following


Command valid?
$ mkdir java classes

This command will create two directories java and classes.


To create a single directory we have to use:
$ mkdir "java classes"

Note: In file or directory names, it is not recommended to use space. Instead of that we
have to use _ symbol like java_classes.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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} y/y1/y1{1,2}

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
29  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q10) To Remove Directories dir1, dir2, dir3.... dir10


If Directories are Empty  $ rmdir dir{1..10}
If Directories are non Empty  $ rm -R dir{1..10}

Q11) To Remove 3 Empty Directories dir2, dir4, dir6


$ rmdir dir{2,4,6}

Q12) To Remove Directories where Name contains 2 OR 4  $ rmdir *[24]*

Q13) To Remove Directories where Name Starts with 'd'  $ rmdir d*

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 vs Relative Path:


Absolute Path: It is the path from root(/) to destination. ie it is complete path.
Relative Path: It is the path from current working directory to destination directory.It is
always wrt current location.

$ mkdir -p x/x{1,2} x/x1/x1{1,2} y/y{1,2} y/y1/y1{1,2}

Eg 1: Assume we are in x11 directory. To change to y2 directory

Absolute Path:
$ cd /home/durga/y/y2
$ cd ~/y/y2
Relative Path:
$ cd ../../../y/y2

nd
DURGASOFT, # 202, 2 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 ../../../y/y2/y21

4) Copy Command (cp)

1) To Copy from File1 to File2 (File to File)


 $ cp source_file destination_file
 $ cp file1 file2
 Total content fo file1 will be copied to file2.
 If file2 is not already available, then this command will create that file.
 If file2 is already available and contains some data, then this data will be over write
with file1 content.

2) To Copy File to Directory:


 $ cp file1 file2 output
 file1 and file2 will be copied to output directory.
 Here we can specify any number of files, but last argument should be directory.
 output directory should be available already.

3) To Copy all Files of One Directory to another Directory:


 $ cp dir1/* dir2
 All files of dir1 will be copied to dir2
 But dir2 should be available already.

4) To Copy Total Directory to another Directory:


 $ cp dir1 dir2
 cp: -r not specified; omitting directory 'dir1'

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
31  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

 Whenever we are copying one directory to another directory, compulsory we should


use -r option.

 $ 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.

5) To Copy Multiple Directories into a Directories:


 $ cp -r dir1 dir2 dir3 dir4 dir5
 dir1,dir2,dir3 and dir4 will be copied to dir5

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.

Moving and Renaming Directories:


Both moving and renaming activities can be performed by using single command: mv

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 of all files from one directory to another directory:


$ mv dir1/* dir2
All files of dir1 will be moved to dir2. After executing this command dir1 will become
empty.

5) Moving total directory to another directory:


$ mv dir1 dir2
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
32  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: If dir2 is already available then dir1 will be moved to dir2. If dir1 is not already
available then dir1 will be renamed to dir2.

Summary of Directory related Commands:


mkdir dir1
mkdir dir1 dir2 dir3
mkdir dir1/dir2/dir3
mkdir -p dir1/dir2/dir3
mkdir dir{1..6}

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 -

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
33  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-6: Working with


Files
1) Creation of Files
2) Viewing of Files
3) Copying of Files
4) Comparison of Files
5) Renaming of files
6) Deleting Files
7) Creation of Hidden files and directories
8) Creation of Link Files
9) Editing of Files

1) Creation of Files:
In Linux, we can create files in the following ways:
1) By using touch command (to create empty file)
2) By using cat command
3) 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.

cat >> file1.txt


extra content
ctrl+d
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
34  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q1) What is the difference between Touch and Cat?


touch for creating empty file where as cat for creating a file with some content.

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
35  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: We can use touch command for the following two purposes:
1) To create an empty file.
2) To change timestamp of existing file.

2) View Content of the Files


We can view content of the file by using the following commands
1) cat
2) tac
3) rev
4) head
5) tail
6) less
7) more

1. View Content of the File by using cat Command:


$ cat < file1.txt OR $ cat file1.txt
< is optional

durga@durga-VirtualBox:~$ cat < file1.txt


This is first line
This is second line
This is third line
This is extra line
durga@durga-VirtualBox:~$ cat file1.txt
This is first line
This is second line
This is third line
This is extra line

While viewing file content we can include line numbers by using -n option.

durga@durga-VirtualBox:~$ cat -n file1.txt


1 This is first line
2 This is second line
3 This is third line
4 This is extra line

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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
36  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

durga@durga-VirtualBox:~$ cat -b file1.txt


1 This is first line

2 This is second line

3 This is third line

4 This is extra line

We can view multiple files content at a time by using cat command.


$ cat file1.txt file2.txt file3.txt

Note: The word cat derived from "con'cat'enation"

Various utilities of cat Command:


1) To create new file with some content
$ cat > filename
data
ctrl+d

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

5) To copy content of multiple files to a single file


$ cat file1.txt file2.txt file3.txt > file4.txt

6) Merging/appending of one file content to another file


$ cat file1.txt >> file2.txt

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
37  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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.

durga@durga-VirtualBox:~$ cat abc.txt


CAT
RAT
MAT
durga@durga-VirtualBox:~$ tac abc.txt
MAT
RAT
CAT

3. rev Command:
rev means reverse.
Here each line content will be reversed.
It is horizontal reversal.

durga@durga-VirtualBox:~$ cat abc.txt


CAT
RAT
MAT
durga@durga-VirtualBox:~$ rev abc.txt
TAC
TAR
TAM

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.

✽ head -n 30 file1.txt OR head -30 file1.txt


 To display top 30 lines of the file.
 Instead of 30 we can specify any number.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
38  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

✽ head -n -20 file1.txt


To display all lines of file1.txt except last 20 lines.

✽ head -c 100 file1.txt


To display first 100 bytes of file content.

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 30 file1.txt OR tail -30 file1.txt OR tail -n -30 file1.txt


It will display last 30 lines.

✽ tail -n +4 file1.txt
It will display from 4th line to last line

✽ tail -c 200 file1.txt


It will display 200 bytes of content from bottom of the file.

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
39  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

less file1.txt
It will display first page

d  To go to next page.(d means down)


b  To go to previous page. (b means backward)

Eg: Assume a file contains enough data. Write command to display from 3 rd 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

head -7 demo.txt | tail -5


3. Karishma Kapoor
4. Sunny Leone
5. Mallika Sharawath
6. Sonakshi Sinha
7. Alia Butt

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
40  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

From 21st line to 30th line:


head -30 demo.txt | tail -10

Creation of Hidden Files and Directories:


 If any file starts with '.' , such type of file is called hidden file.
 If we don't want to display the files then we have to go for hidden files.
 Hidden files meant for hiding data. All system files which are internally required by
kernal are hidden files.
 We can create hidden files just like normal files, only difference is file name should
starts with dot.

touch .securefile1.txt
cat > .securefile1.txt
Even by using editors also we can create hidden files.

We can create hidden directories also just like normal directories.

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.

Interconversion of Normal Files and Hidden Files:


Based on our requirement, we can convert normal file as hidden file and viceversa.

mv a.txt .a.txt
We are converting normal file a.txt as hidden file.

mv .a.txt a.txt

Similarly directories also

mv dir1 .dir1
mv .dir1 dir1

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
41  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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'?

If we want verbose output then we can use -v option.


cp -v file1.txt file2.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.

cp a.txt b.txt c.txt d.txt  Invalid


cp: target 'd.txt' is not a Directory

cat a.txt b.txt c.txt > d.txt  Valid

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
42  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Moving and Renaming Directories:


Both moving and renaming activities can be performed by using single command: mv

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

3) Moving of files from one directory to another directory:


 mv dir1/* dir2
 All files of dir1 will be moved to dir2. After executing this command, dir1 will come
empty.

4) Move total directory to another directory:


 mv dir1 dir2
 dir1 will be moved to dir2
 In the case of overwriting, if we want confirmation alert then we can use -i option
with mv command.
 $ mv -i a.txt d.txt dir1
 mv: overwrite 'dir1/a.txt'?

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
43  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

cmp file1.txt file2.txt


If content is same then we won't get any output.
If the content is different, then it provides information about only first difference. byte
number and line number will be provided.

$ cmp a.txt c.txt


a.txt c.txt differ: byte 7, line 2

Note: cmp command won't show all differences and show only first difference.

2) diff Comamnd:
It will show all differences in the content.

diff file1.txt file2.txt


If the content is the same then no output.
If the content is different then it will show all differences.

$ diff a.txt b.txt


$ diff a.txt c.txt
2,3c2,3
< Bunny
< Chinny
---
> bunny
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
44  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

> chinny
b

For the diff command we can use the following options.


-q shows message when files are different.
-s shows message when files are same | identical
-y shows comparison line by line (parallel comparison)

$ diff -q a.txt c.txt


Files a.txt and c.txt differ
$ diff -s a.txt b.txt
Files a.txt and b.txt are identical
$ diff -y a.txt c.txt
Sunny Sunny
Bunny | bunny
Chinny | chinny
Vinny Vinny
Pinny Pinny

If we want to suppress common lines then we should use --suppress-common-lines option


with -y option.

$ diff -y --suppress-common-lines a.txt c.txt


Bunny | bunny
Chinny | chinny

3) sdiff Command:
We can use sdiff command for side by side comparison (parallel comparison)

$ sdiff a.txt b.txt


Sunny Sunny
Bunny Bunny
Chinny Chinny
Vinny 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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
45  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

4) vimdiff Command:
 It will highlight differences in vim.

 To support this command, we have to install vim by using the following command.
 sudo apt install vim

 vimdiff a.txt b.txt

 ctrl+w+w  To go to next window


 :q  Close current window
 :qa  Close all windows
 :qa!  Close all windows forcely.

5) comm Command:
By using this command we can compare data of two files.

comm file1.txt file2.txt

It display results in 3 columns

column-1: Data present only in file1.txt but not in file2.txt


column-2: Data present only in file2.txt but not in file1.txt
column-3: Common data of both files.

$ comm a.txt c.txt


Sunny
bunny
Bunny
chinny
Chinny
Vinny

Pinny

With comm command we can use the following options

-1 If we don't want to display column-1


-2  If we don't want to display column-2
-3  If we don't want to display column-3
-12  If we don't want to display columns 1 and 2

Note: We can compare files from various builds by using our comparison commands
(cmp, diff, sdiff, vimdiff, comm).
nd
DURGASOFT, # 202, 2 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:

mkdir -p x/x1/x1{1,2} x/x2 y/y1/y1{1,2} y/y2

durgasoft@durgasoft-VirtualBox:~$ cat > x/x1/x11/file1.txt


This is file1 content
This is file1 content

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
47  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-9: Creation of
Link Files
There are 2 types of link files
1) Hard Link files
2) Soft Link files

1) Hard Link Files:

It is just another name of the same exact file.


We can create hard link file by using ln command.
ln originalfile hardlinkfile

Eg: ln file1.txt file2.txt


Here file1.txt is original file and file2.txt is hard link file.

Important conclusions about hard link file:


1) Both original file and hardlink file have same inode number, same size, same
timestamp.
2) If we delete original file, then there is no effect on hardlink file.

2) Soft Link File:


 A softlink is a pointer to another file. It is just like windows shortcut.
 It is also known as symbolic link.
 We can create soft link file by using ln command but with -s option.
 ln -s originalfile softlinkfile

 Eg: ln -s file1.txt file2.txt


 Here file1.txt is original file and file2.txt is link file.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
48  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Important conclusions about softlink file:


1) Original file and softlink file have different inode numbers, different file sizes and
different timestamps.
2) Usually softlink file has smaller file size than original file size.
3) If we delete original file then softlink files will become useless.

Link files for directories:


We cannot create hardlink for directories because it breaks Linux File System. Having two
root directories is meaningless.

$ ln dir1 dir2
ln: dir1: hard link not allowed for directory

We can create softlink for directories


$ ln -s dir1 dir2

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

dir1  dir2  dir3

$ mkdir -p dir1/dir2
$ cd dir1/dir2
$ ln -s ~/Desktop/dir1 dir3

It will form a loop.

Note: While creating link files there may be a chance of forming loops. Take a bit special
care.

Q1) Which of the following is valid about Hard Link?


A) Inode number is different when compared to that of original file.
B) File Size is different when compared to that of original file.
C) It will become useless if we delete original file.
D) Inode number, file size and timestamp are same when compared to that of
original file.

Ans: D

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
49  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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?
A) True
B) 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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
50  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-10: Word Count


Command (wc Command)
We can use wc command to count number of lines, words and characters present in the
given file.

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)

We can use the following options with wc Command

-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.

$ wc -l a.txt
4 a.txt
$
$ wc -w a.txt
26 a.txt
$ wc -c a.txt
166 a.txt
$ wc -lw a.txt
4 26 a.txt
$ wc -lc a.txt
4 166 a.txt
$ wc -wc a.txt
26 166 a.txt

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
51  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

$ wc -L a.txt
57 a.txt

We can use wc command for multiple files simultaneously.


$ 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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
52  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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 alphabetical 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 symbols.
$ cat a.txt
7
Sunny
8
Bunny
1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
53  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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.

$ cat > a.txt


11
2
7
2222222
9

$ sort a.txt
11
2
2222222
7
9
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
54  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

If we want to sort based on numeric value then we have to use -n option.


-n means numeric value

$ 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
Bunny
$ sort a.txt
1
1
2
2
Bunny
Sunny
Sunny
$ sort -u a.txt
1
2
Bunny
Sunny

Note: We can use -ur and -un options also.


To play with unique data, there is special command available: uniq

Q1) Assume a.txt contains the following Data


Sunny
Bunny
Chinny
Vinny
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
55  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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?

sort a.txt | tac > sorted.txt


sort -r a.txt > sorted.txt

To remove duplicate lines also:

sort -u a.txt | tac > sorted.txt


sort -ru a.txt > sorted.txt

Sorting Tabular Data by using -k Option:


-k means KEYDEF (key definition). Based on which key (column) we have to sort.

$ ls -l /etc | head -10


total 1068
drwxr-xr-x 3 root root 4096 Aug 6 00:34 acpi
-rw-r--r-- 1 root root 3028 Aug 6 00:28 adduser.conf
drwxr-xr-x 2 root root 4096 Nov 7 19:47 alternatives
-rw-r--r-- 1 root root 401 May 29 2017 anacrontab
-rw-r--r-- 1 root root 433 Oct 2 2017 apg.conf
drwxr-xr-x 6 root root 4096 Aug 6 00:30 apm
drwxr-xr-x 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

Sort based on File Size in ascending Order:


$ ls -l /etc | head -10 | sort -k 5n
total 1068
-rw-r--r-- 1 root root 401 May 29 2017 anacrontab
-rw-r--r-- 1 root root 433 Oct 2 2017 apg.conf
-rw-r--r-- 1 root root 3028 Aug 6 00:28 adduser.conf
drwxr-xr-x 2 root root 4096 Nov 7 19:47 alternatives
drwxr-xr-x 3 root root 4096 Aug 6 00:33 apparmor
drwxr-xr-x 3 root root 4096 Aug 6 00:34 acpi
drwxr-xr-x 4 root root 4096 Nov 7 06:33 apport
drwxr-xr-x 6 root root 4096 Aug 6 00:30 apm
drwxr-xr-x 8 root root 4096 Nov 7 06:32 apparmor.d

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
56  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Sort based on Month:


6th column provides total date. If we want consider only month then we should use M.

$ ls -l /etc | head -10 |sort -k 6M


total 1068
-rw-r--r-- 1 root root 401 May 29 2017 anacrontab
drwxr-xr-x 3 root root 4096 Aug 6 00:33 apparmor
drwxr-xr-x 3 root root 4096 Aug 6 00:34 acpi
drwxr-xr-x 6 root root 4096 Aug 6 00:30 apm
-rw-r--r-- 1 root root 3028 Aug 6 00:28 adduser.conf
-rw-r--r-- 1 root root 433 Oct 2 2017 apg.conf
drwxr-xr-x 2 root root 4096 Nov 7 19:47 alternatives
drwxr-xr-x 4 root root 4096 Nov 7 06:33 apport
drwxr-xr-x 8 root root 4096 Nov 7 06:32 apparmor.d

Sort based on Number of Links in descending Order:


$ ls -l /etc | head -10 |sort -k 2nr
total 1068
drwxr-xr-x 8 root root 4096 Nov 7 06:32 apparmor.d
drwxr-xr-x 6 root root 4096 Aug 6 00:30 apm
drwxr-xr-x 4 root root 4096 Nov 7 06:33 apport
drwxr-xr-x 3 root root 4096 Aug 6 00:33 apparmor
drwxr-xr-x 3 root root 4096 Aug 6 00:34 acpi
drwxr-xr-x 2 root root 4096 Nov 7 19:47 alternatives
-rw-r--r-- 1 root root 3028 Aug 6 00:28 adduser.conf
-rw-r--r-- 1 root root 401 May 29 2017 anacrontab
-rw-r--r-- 1 root root 433 Oct 2 2017 apg.conf

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
57  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-12: Find Unique


Content in the File by using
uniq Command
We can use uniq command to display unique content in the file.
But to use uniq command, compulsory the file should be sorted, otherwise it won't work
properly.

$ cat a.txt
Sunny
sunny
Bunny
Chinny
Sunny
Bunny
Chinny

$ uniq a.txt
Sunny
sunny
Bunny
Chinny
Sunny
Bunny
Chinny

$ sort a.txt | uniq


Bunny
Chinny
sunny
Sunny

With uniq command we can use multiple options:


-d  To display only duplicate lines
-c  To display number of occurrences of each line
-i  Ignore case while comparing
-u  To display only unique lines i.e the lines which are not duplicated.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
58  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

1. To display only duplicate lines:


$ sort a.txt | uniq -d
Bunny
Chinny
Sunny

2. To display number of occurrences of each 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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
59  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-13: Input and Output of Commands


and Redirection

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.

These data streams are associated with some numbers.


Standard Input associated with 0.
Standard Output associated with 1.
Standard Error associated with 2.

Bydefault Standard input connected with keyboard, Standard output and Standard Error
connected with Terminal. But we can redirect.

Standard Input from the keyboard and output to Standard Ouput


Device:
$cat
read required input from the keyboard
this data will be displayed to the standard output.
ctrl+d

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).
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
60  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

$ cat
This is data provided from Standard Input
This is data provided from Standard Input

Input from command line arguments and error messages to the


Standard Error:
$ rm file100
rm: cannot remove 'file100': No such file or directory

We are providing filename as command line argument to the rm command.


Specified file not available and hence this command will produces error message to the
Standard Error 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.

Redirecting Standard Ouput:


We can redirect standard output by using > and >> symbols.

> will perform overwriting of existing data


>> will perform appending to existing data

Eg 1: To redirect the standard output of cat command from terminal to output.txt

$cat 1> output.txt


sample data
ctrl+d

sample data won't be displayed to the terminal and will write to output.txt

Redirection symbol > is always associated with 1 by default. Hence we are not required to
specify 1 explicilty.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
61  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

$cat > output.txt


sample data
ctrl+d

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.

$ cal 34 w3892384208342 2>> error.txt

Now error message won't be displayed to the console and will written to error.txt.
For error redirection 2 is mandatory.

Redirecting Standard Input:


We can redirect standard input from keyboard to our required file.
We can perform input redirection by using < symbol.

$cat 0< a.txt 1>>output.txt 2>>error.txt

< symbol is always associated with 0 by default. Hence we can remove.


$cat < a.txt >>output.txt 2>>error.txt

***Note: To redirect both standard output and standard error to the same destination we
can use shortcut as follows

$ cat < a.txt &> output.txt


&> means both standard output and standard error.

Redirecting Standard output from one terminal to another


terminal:
In unix every thing is treated as file even our terminal also.
We can find terminal related file by using tty command.

termainal - 2:
$ tty
/dev/pts/1

terminal - 1:
$ls -l 1> /dev/pts/1

terminal-1 long listing output will be displayed to terminal-2


nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
62  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Bits
Q1) In How Many Ways Command can get Input?
2 ways. Either from Standard Input or from command line arguments.

Q2) Which of the following contains Data Streams?


A) Standard Input
B) Standard Output
C) Standard Error
D) Command Line arguments
Ans: A,B,C

Q3) By Default Standard Input connected to


A) Terminal
B) Keyboard
C) A File
Ans: B

Q4) By Default Standard Ouput connected to Terminal

Q5) By Default Standard Error connected to Terminal

Q6) What Number represents Standard Input Stream? 0

Q7) What Number represents Standard Output Stream? 1

Q8) What Number represents Standard Error? 2

Q9) How we can redirect Standard Output of the ls


Command to a File called Output.txt?
A) ls 2> output.txt
B) ls 0< output.txt
C) ls 1< output.txt
D) ls 1> output.txt
Ans: D
ls 2> output.txt  redirecting standard error from terminal to output.txt
ls 0< output.txt  redirecting standard input from keyboard to output.txt
ls 1< output.txt  Meaningless

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
63  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q10) How we can redirect the Standard Output of the ls


Command to Output.txt, but at the Same Time,
redirect Standard Error to error.txt?
ls 1> output.txt 2> error.txt
ls > output.txt 2> error.txt

Q11) Explain the difference between <, >, >> in Redirection?


< symbol meant for input redirection
> symbol meant for output redirection where the existing data will be overwritten.
>> symbol meant for output redirection where the data will be appended instead
of overwriting.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
64  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

We can implement piping by using vertical bar (|).

$ 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 support.

tee Command:
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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
65  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

tee command is just like T-Junction or T-Pipe. It will take one input but provides two
outputs.

Eg 1: To save the output of ls command to a file and to display to the terminal


simultaneously.

$ ls –l  It will display to the terminal


$ ls -l > abc.txt  It will save to the abc.txt but won't display to the terminal.
$ ls -l | tee abc.txt

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
66  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

$ cat input.txt | xargs cat | tee output.txt | wc -l

Eg 2: Assume input.txt contains file names. Read file names from the input.txt and remove
all these files.

$ cat input.txt | xargs rm

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

Write a single pipeline for the following requirement:


read content of file1 and file2, save to fil3.txt. By using sort command reverse contents of
file3.txt and save to sorted.txt.

$ ls /dev > file1.txt


$ ls /bin > file2.txt
$ cat file1.txt file2.txt | tee file3.txt | sort -r > sorted.txt

Q2) What is Piping?


A) A way of connecting commands together.
B) A way of passing data from the standard output of one command to the standard
input of another command.
Ans: A,B

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
67  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q3) How to Pipe Standard Output of X Command to the


Standard Input of Y Command?
A) X > Y
B) X >> Y
C) X < Y
D) X | Y
Ans: D

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
68  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-15: How to Use Multiple


Commands in a Single Line
We can execute multiple independent commands in a single line by using the following
two ways

1st Way: By using semicolon (;)


cmd1;cmd2;cmd3;.....;cmdn

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.

2nd Way: By using &&


cmd1 && cmd2 && cmd3 &&..... && cmdn

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
mkdir dir1 && touch dir1/{a,b,c}.txt && date > dir1/a.txt && cal > dir1/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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
69  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-16: Regular Expressions and Wildcard


Characters
If we want to represent a group of strings according to a particular pattern, then we
should go for regular expressions.

By using wildcard characters, we can build regular expressions.

A wildcard character can be used as a substitute for required sequence of characters in the
regular expression.

1)  Represents zero or more characters


2) ?  Represents only one character
3) [] Range of characters
4) [abc]  Either a or b or c
5) [!abc] Any character except a,b and c
6) [a-z]  Any lower case alphabet symbol
7) [A-Z]  Any upper case alphabet symbol
8) [a-zA-Z]  Any alphabet symbol
9) [0-9]  Any digit from 0 to 9
10) [a-zA-Z0-9]  Any alphanumeric character
11) [!a-zA-Z0-9]  Except alpha numeric character (i.e special symbol)
12) [[:lower:]]  Any lower case alphabet symbol
13) [[:upper:]]  Any upper case alphabet symbol
14) [[:alpha:]]  Any alphabet symbol
15) [[:digit:]]  Any digit from 0 to 9
16) [[:alnum:]]  Any alpha numeric character
17) [![:digit:]]  Any character except digit
18) {}  List of files with comma separator

1) To list out all files present in current working directory  $ ls *

2) To list out all files with some extension  $ ls *.*

3) To list out all files starts with a  $ ls a*

4) To list out all files starts with a and ends with t  $ ls a*t

5) To list out all .java files  $ ls *.java

6) To list out all files where file name contains only 2 characters and first character
should be 'a'  $ ls a?

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
70  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

7) To list out all files where file name contains only 3 characters  $ ls ???

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:]]*

13) To list out all files starts with digit.


$ ls [0-9]* OR $ls [[:digit:]]*

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:]]

15) To list out all files starts with special symbol


$ls [![:alnum:]]*

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

17) To copy all files starts with digit to dir1 directory.


$cp [[:digit:]]* dir1
$cp [0-9]* dir1

18) To move all files starts with alphabet symbol and with .txt extension to dir2 directory?
$mv [[:alpha:]]*.txt dir2

19) Remove all files starts with a or b or c and ends with e or t.


$rm [abc]*[et]

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
71  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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?
A) cp ?.pdf dir1
B) cp .pdf* dir1
C) 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

Q4) Which of the following Commands will display Contents of all


Files that begins with a Digit and Ends with Letter a OR e OR i
OR o OR u?
$cat [[:digit:]]*[aeiou]
$cat [0-9]*[aeiou]

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
72  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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

Q8) Which of the following Regular Expressions can Match the


Files?
student_reportA.pdf
student_reportB.pdf
student_reportC.pdf

A) ??.pdf
B) report*.pdf
C) *[A-Z].pdf
D) student*.pdf

Ans: C, D

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
73  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

How to Create Alias Names?


$ alias nickname='original command'
$ alias nickname="original command"

After aliasname space is not allowed. Hence the following are invalid
alias nickname ='original command'
alias nickname= 'original command'
alias nickname = 'original command'

How to List all available Aliases?


By using alias command without any arguments
$alias

How to Remove Alias Names?


By using unalias command.
$unalias alias_name

Where we can use aliasing:


1. If any lengthy command repeatedly required, then we can create shortcut alias name
and we can use that short alias name every time.

alias d20f='mkdir dir1;touch dir1/file{1..20}.txt'

$d20f

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
74  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg: To list out all files present in current working directory, save this data to output.txt
and display the number of lines to the terminal. Define alias name 'current' for this total
activity.

alias current='ls -l | tee output.txt | wc -l'

2. To use other operating system (like windows) commands directly in linux

alias cls='clear'
alias rename='mv'

3. To handle typing mistakes

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

Add the following lines in that file.

# myown aliases
alias cls='clear'
alias ddd='date;date;date'

Note: To reflect these aliases, compulsory we have to close and open terminal.

2nd Way:
Instead of editing .bashrc file, we can create our own file to maintain our defined aliases.
The name of the file should be .bash_aliases and should be present in home directory.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
75  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

.bash_aliases
alias ccc='cal;cal;cal'
alias ct='cal;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

Q3) To Persist Aliases, in which File we have to define Aliases?


.bashrc OR .bash_aliases

Q4) Which of the following is Valid Way of creating Alias?


A) alias rename ="mv"
B) alias rename= "mv"
C) alias rename = "mv"
D) alias rename="mv"

Ans: D

While creating aliases, we should not give space.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
76  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-18: Locate and Find


Commands
locate Command:
We can use locate command to locate files and directories in our system.

Internally locate command will search in the database for the required files and
directories and returns the results.

As locate command is searching in the database instead of filesystem, performance will be


improved.

1. To locate all .jpg files


$ locate *.jpg

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

Note: In ubuntu -i option is not working

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

It display only 5 lines.

Before display results, to check whether the file exists or not , we have to use -e option or
--existing option.

$locate --existing *jpg

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
77  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Reason:
locate command using database to find results. This database will be updated only once
per day bydefault. After updating database, some files may be deleted. Hence before
printing results, to check whether files are existing or not, we have to use -e or --existing
option.
Before displaying results, to check whether symbolic links pointing to original files or not,
we have to use -L or --follow option. i.e if we use --follow option, broken symbolic links
won't be displayed in the output.

$locate --follow *.txt

Note: We can use all these options together

$locate --existing --follow -i --limit 5 *.conf | wc -l

observe the difference in results:


$locate *.conf | wc -l
$locate -i *.conf | wc -l
$locate --existing -i 5 *.conf | wc -l
$locate --existing --follow -i *.conf | wc -l
$locate --existing --follow -i --limit 10 *.conf | wc -l

How to Update Database?


We can see the database by using locate command with -S 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:

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
78  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q1) Which of the following are Valid Options to locate Command?


A) -i
B) --limit
C) -L
D) -e
E) --existing
F) --follow
G) All of these
And: G

Q2) Locate Command internally Uses Database to find Results?


True
False
Ans: True

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?
A) Yes
B) No
Ans: No

Q4) How to Update Database which is used by locate Command?


A) update locatedb
B) updatedb
C) sudo updatedb
Ans: C

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
79  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
|-level_1_dir
|-file2.txt
|-levlel_2_dir
|-file3.txt
|-level_3_dir
|-file4.txt
|-level_4_dir
|-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

Observe the difference in results by executing the following commands:

1. $ find . -maxdepth 1
2. $ find . -maxdepth 2
3. $ find . -maxdepth 3
4. $ find . -maxdepth 4
5. $ find . -maxdepth 100

Note:
1. For maxdepth option we should use singl - but not double --
-maxdepth  Valid
--maxdepth  Invalid
2. find command will find hidden files and directories also.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
80  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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

durgasoft@durgasoft-VirtualBox:~/Desktop$ find -type f


./level_1_dir/file2.txt
./level_1_dir/level_2_dir/file3.txt
./level_1_dir/level_2_dir/level_3_dir/level_4_dir/file5.txt
./level_1_dir/level_2_dir/level_3_dir/file4.txt
./file1.txt
./.securefile1.txt

durgasoft@durgasoft-VirtualBox:~/Desktop$ find -type d


.
./.db_info
./level_1_dir
./level_1_dir/level_2_dir
./level_1_dir/level_2_dir/level_3_dir
./level_1_dir/level_2_dir/level_3_dir/level_4_dir

Note: We can use these options simultaneously, but we should use first -maxdepth and
then -type.

$find -type f -maxdepth 2  Generates warning


$find -maxdepth 2 -type f  No warnings

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

$ find . -name 'A.txt'


$ find . -name '?.txt'
$ find . -name '??.txt'
$ find . -name '*.txt'
$ find . -maxdepth 2 -name '*.txt'

If we want to ignore case then we should use -iname option.


$ find -iname 'a.txt'

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
81  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Find Files by Size:


We should use -size option.
+ symbol means greater than (over)
- symbol means less than

1. To list out all file names where size is over 200kb


$ find / -type f -size +200k This command required root privileges
$ sudo find / -type f -size +200k | wc -l

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

Q1) What is the Output of the following Command?


$ find / -type f -size -200k -size +4M | wc -l
The answer should be: 0

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?
$ find /etc -type f -size -2k -exec cp {} dir1 \;

Before performing required copy operation if we want confirmation then we


should use -ok option instead of -exec.
$ find /etc -type f -size -2k -ok cp {} dir1 \;

durgasoft@durgasoft-VirtualBox:~/Desktop$ find /etc -type f -size -2k -ok cp {} dir1


\;
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
82  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

< cp ... /etc/magic.mime > ? y


< cp ... /etc/fwupd/uefi.conf > ? y
< cp ... /etc/fwupd/daemon.conf > ? y

Magic Assignment:
$ mkdir magic
$ mkdir magic/dir{1..100}
$ touch magic/dir{1..100}/file{1..100}.txt

$ mkdir magic;mkdir magic/dir{1..100};touch magic/dir{1..100}/file{1..100}.txt

$ touch magic/dir$(shuf -i 1-100 -n 1)/sunny.txt

$ find magic -type f -name 'sunny.txt'


$ find magic -type f -name 'sunny.txt' -exec mv {} ~/Desktop \;
$ find magic -type f -name '*.txt' -exec rm {} \;

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?
A) find -start /dev -depth 2
B) find /dev -depth 2
C) find /dev -maxdepth 2
Ans: C

Q6) To find only Directories inside /dev Folder and Limit its Search to only 2
Levels of Deep?
A) find /dev -maxdepth 2 -type f
B) find /dev -maxdepth 2 -type d
C) find /dev -type d -maxdepth 2
Ans: B

Q7) To find only Files Starts from Root Directory (/) where File Name Ends
with .txt?
A) find / '*.txt'
B) find / -type d -name '*.txt'
C) find / -type f -name '*.txt'
Ans: C

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
83  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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?
A) find ~ -type f -size +3M -exec rm {} \;
B) find ~ -type f -size -3M -exec rm {}
C) find ~ -type f -size -3M -exec rm {} \;
D) find ~ -type f -size +3M rm {} \;

Ans: A

Difference between find and locate Commands

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
84  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-19: Compression and Uncompression


of Files (tar, gzip, gunzip, bzip2, bunzip2)
As the part of admin activity, it is very common requirement to pack and compress a
group of files. The main advanatages are:

1) It improves memory utilization


2) Transportation will become very easy
3) It reduces download times
etc

This process involves the following 2 activities:


1) Creation of Archive file
2) Apply compression algorithms on that archive file

1) Creation of Archive File


We can group multiple files and directories into a single archive file by using tar
command.

tar  tape archive

A) To create tar file


tar -cvf demo.tar file1.txt file2.txt file3.txt
tar -cvf demo.tar *

B) To display table of contents of tar file


tar -tvf demo.tar

C) To Extract contents of tar file


tar -xvf demo.tar

2) Apply Compression Algorithms on that Archive File:


There are multiple compression and decompression algorithms.
1) gzip  It is very fast but less compression power
2) bzip2  It is a bit slow but more compression power

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
85  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Compression and Decompression by using gzip:


1) To Compress tar file
$ gzip demo.tar
demo.tar.gz  This file got created

2) To uncompress gz file:
$ gzip -d demo.tar.gz OR $ gunzip demo.tar.gz
 This command will provide our original tar file

Compression and Decompression by using bzip2:


1. To compress tar file:
$ bzip2 demo.tar
demo.tar.bz2 this file will be created.

2. To uncompress bz2 file:


$ bunzip2 demo.tar.bz2

How to create tar File and compress in a Single Command:


1. By using gzip compression algorithm

To create tar and then compress


$ tar -cvzf demo.tar *.txt
z option will do compression
demo.tar will be created and it is already compressed

To uncompress and extract tar file


$ tar -xvzf demo.tar

2. By using bzip2 compression algorithm


Instead of 'z', we have to use 'j'

To create tar and then compress


$ tar -cvjf demo.tar *.txt
j option will do compression
demo.tar will be created and it is already compressed

To uncompress and extract tar file


$ tar -xvjf demo.tar

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
86  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Use Case: Backup of Total User Home Directory


$ pwd
/home/durgasoft
$ tar -cvzf backup.tar *

$mkdir newhome
$mv backup.tar newhome
$cd newhome
$ tar -xvzf backup.tar

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
87  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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 <pattern> filename

It prints all matched lines.

durgasoft@durgasoft-VirtualBox:~/Desktop$ cat subjects.txt

Sno Subjectname Faculty Fee


1. Python Nagoor 1000
2. Java Sriman 2000
3. Unix Durga 250
4. DevOps Sriman 3500
5. UNIX Durga 400
6. Java Durga 1000

1) To Search Data in a Single File:


$ grep 'durga' subjects.txt
$ grep "durga" subjects.txt
$ grep durga subjects.txt

it prints all matched lines.

3. Unix durga 250


5. UNIX durga 400
6. Java durga 1000

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

2) To Search in Multiple Files:


$ grep durga subjects.txt career.txt
subjects.txt:3. unix durga 250
subjects.txt:5. UNIX durga 400
subjects.txt:6. Java durga 1000
career.txt:durga
career.txt:durga ksdjfdlakjklfjad

$ grep durga *.txt


career.txt:durga
career.txt:durga ksdjfdlakjklfjad
subjects.txt:3. unix durga 250
subjects.txt:5. UNIX durga 400
subjects.txt:6. Java durga 1000

$ grep durga *
career.txt:durga
career.txt:durga ksdjfdlakjklfjad
subjects.txt:3. unix durga 250
subjects.txt:5. UNIX durga 400
subjects.txt:6. Java durga 1000

3) To Search Data by ignoring Case:


Bydefault grep command will consider case. If we want to ignore case then we should use
use -i option.

durgasoft@durgasoft-VirtualBox:~/Desktop$ grep unix *.txt


career.txt:unix jksadjfklasjdkflajs
subjects.txt:3. unix durga 250
durgasoft@durgasoft-VirtualBox:~/Desktop$ grep -i unix *.txt
career.txt:unix jksadjfklasjdkflajs
subjects.txt:3. unix durga 250
subjects.txt:5. UNIX durga 400

4) To Display the Number of Occurrences:


We have to use -c option.
c means count

$ grep -c unix *.txt


career.txt:1
subjects.txt:1

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
89  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

5) To Display Line Numbers before Results:


We have to use -n option.

durgasoft@durgasoft-VirtualBox:~/Desktop$ grep -n is *.txt


career.txt:1:Java  It is ocean but ever green!!!!
durgasoft@durgasoft-VirtualBox:~/Desktop$ grep -n durga *.txt
career.txt:4:durga
career.txt:7:durga ksdjfdlakjklfjad
subjects.txt:4:3. unix durga 250
subjects.txt:6:5. UNIX durga 400
subjects.txt:7:6. Java durga 1000

6) To Display only File Names in which Pattern exists:


We have to use -l option.

durgasoft@durgasoft-VirtualBox:~/Desktop$ grep -l durga *.txt


career.txt
subjects.txt

7) To Print except matched Lines remaining Lines:


We have to use -v option. It means inverted.

durgasoft@durgasoft-VirtualBox:~/Desktop$ grep durga subjects.txt


3. unix durga 250
5. UNIX durga 400
6. Java durga 1000
durgasoft@durgasoft-VirtualBox:~/Desktop$ grep -v durga subjects.txt
sno subjectname faculty fee
1. Python Nagoor 1000
2. java Sriman 2000
4. devops sriman 3500

8) To Search for exact word in the File:


For this we have to use -w option.

Eg 1:
durgasoft@durgasoft:~/Desktop$ grep -i unix demo.txt
UnixDemo session
unix material
durgasoft@durgasoft:~/Desktop$ grep -iw unix demo.txt
unix material

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
90  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg 2:
durgasoft@durgasoft:~/Desktop$ grep -in unix demo.txt
5:UnixDemo session
6:unix material
9:UNIX classes and videos
durgasoft@durgasoft:~/Desktop$ grep -win unix demo.txt
6:unix material
9:UNIX classes and videos

9) Display before, after and surrounding lines including Search Results:


We have to use -A,-B,-C options

-A means after
-B means before
-C means before and after

durgasoft@durgasoft:~/Desktop$ grep friends demo.txt


Hello friends how are you
durgasoft@durgasoft:~/Desktop$ grep -A 2 friends demo.txt
Hello friends how are you
DataScienceDemo
UnixDemo session
durgasoft@durgasoft:~/Desktop$ grep -B 2 friends demo.txt
This is java demo
this is python demo
Hello friends how are you
durgasoft@durgasoft:~/Desktop$ grep -C 2 friends demo.txt
This is java demo
this is python demo
Hello friends how are you
DataScienceDemo
UnixDemo session

durgasoft@durgasoft:~/Desktop$ grep -2 friends demo.txt


This is java demo
this is python demo
Hello friends how are you
DataScienceDemo
UnixDemo session

Note: C is optional.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
91  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Search Multiple Content in a File:


durgasoft@durgasoft:~/Desktop$ grep -i -e "java" -e "unix" demo.txt
This is java demo
UnixDemo session
unix material
UNIX classes and videos
java is slowly going down

Instead of using -e option, we can use egrep command directly.


It is extended grep. It interprets patterns as an extended reqular expression.

durgasoft@durgasoft:~/Desktop$ egrep -i "(java|unix)" demo.txt


This is java demo
UnixDemo session
unix material
UNIX classes and videos
java is slowly going down

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.

durgasoft@durgasoft:~/Desktop$ grep -F "java


> unix" demo.txt
This is java demo
unix material
java is slowly going down

Instead of using , -F option, we can use directly fgrep.


durgasoft@durgasoft:~/Desktop$ fgrep "java
> unix
> friends
> demo" demo.txt
This is java demo
this is python demo
Hello friends how are you
unix material
java is slowly going down

Note: fgrep can be used only for Strings and cannot be used for regular expressions.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
92  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Normal grep command cannot understand some regular expression patterns like |
symbol. But egrep command can understand any regular expression pattern. Hence egrep
is the more powerful than normal grep command.

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.

durgasoft@durgasoft:~/Desktop$ egrep -i "(java|unix)" 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

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.

durgasoft@durgasoft:~/Desktop$ fgrep -f file1.txt demo.txt


This is java demo
this is python demo
Hello friends how are you
unix material
java is slowly going down

This is java demo


this is python demo
Hello friends how are you
DataScienceDemo
UnixDemo session
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
93  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

unix material
dsfjalkjfdlsda
sadkfjklsadjfkld
UNIX classes and videos
java is slowly going down
demounix
unixforall
grtgrgtujmik, fgtunix dghjhrunix fghubunixdfgghj

file1.txt
java
unix
python
demo
-i,-n,-c,-v,-l,-A,-B,-C,-e,-E, -F,-f, -o, -R

To Print only matched Patterns instead of Total Line:


We have to use -o option.

durgasoft@durgasoft:~/Desktop$ grep c[aeiou]ll demo.txt


call center
cell point
college for unix
durgasoft@durgasoft:~/Desktop$ grep -o c[aeiou]ll demo.txt
call
cell
coll

Q1) Write grep Command to extract only Mobile Numbers present


in the Input File and write to mobile.txt?
$ grep -o [6-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] input.txt > mobile.txt
$ grep -o "[6-9][0-9]{9}" input.txt > mobile.txt  This command won't work because {9}
cannot be understandable by grep command. But egrep can understand.

$ egrep -o "[6-9][0-9]{9}" input.txt > mobile.txt

durgasoft@durgasoft:~/Desktop$ cat demo.txt


call center
cell point
college for unix
extra line 1
extra line2
c[aeiou]ll point for fgrep
durgasoft@durgasoft:~/Desktop$ grep c[aeiou]ll demo.txt
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
94  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

To Search in the Files recursively inside a Directory:


If we want to use grep command for all files present in the specified directory and sub
directory recursively then we should use R option.

resumes
java
students.txt
python
students.txt
testing
students.txt
$ mkdir resumes

durgasoft@durgasoft:~/Desktop$ egrep "[6-9][0-9]{9}" resumes/


grep: resumes/: Is a directory
durgasoft@durgasoft:~/Desktop$ egrep -R "[6-9][0-9]{9}" resumes/
resumes/python/students.txt:Durga 9898989898
resumes/python/students.txt:Ravi 8096969696
resumes/python/students.txt:Shiva 9797975656
resumes/java/students.txt:Durga 9898989898
resumes/java/students.txt:Ravi 8096969696
resumes/java/students.txt:Shiva 9797975656
resumes/testing/students.txt:Durga 9898989898
resumes/testing/students.txt:Ravi 8096969696
resumes/testing/students.txt:Shiva 9797975656

Note: If we want to use grep command for directory, compulsory we should use -R
option, which means recursive.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
95  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Assignment:
1. Save all running processes information inside a file.
$ ps -ef > results.txt

2. Display all lines which contains 'lib'


$ grep 'lib' results.txt

3. Display all lines which does not contain 'lib'


$ grep -v 'lib' results.txt

4. Count all lines where we are getting 'lib'


$ grep -c 'lib' 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. Display all employees belongs to admin department


$ grep 'admin' emp.dat

2. Display all employees in admin and sales department


$ egrep '(admin|sales)' emp.dat

3. Display all male employees in admin and sales department


$ egrep '(admin|sales)' emp.dat | grep -w 'male'

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
96  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Types of Regular Expressions/Patterns:


All Regular expression patterns are divided into 3 types.

1) Character Patterns
2) Word Patterns
3) Line Patterns

1) 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) $ grep 'c[aeiou]ll' demo.txt


It will search for call, cell, cill, coll, cull

3) $ grep 'b..l' demo.txt


. means any character. It will search for all 4 letter words where first letter should
b and last letter should be l.

2) Word Patterns:
\<word\>  It will always searches for the given word
It is exactly same as
grep -w word demo.txt

\<xyz  It will search for the word starts with xyz


xyz\>  It will search for the word ends with xyz

durgasoft@durgasoft:~/Desktop$ cat > demo.txt


durga
durgasoft
techdurga
softwaredurgasolutions

durgasoft@durgasoft:~/Desktop$ grep 'durga' demo.txt


durga
durgasoft
techdurga
softwaredurgasolutions
durgasoft@durgasoft:~/Desktop$ grep '\<durga\>' demo.txt
durga
durgasoft@durgasoft:~/Desktop$ grep '\<durga' demo.txt
durga
durgasoft
durgasoft@durgasoft:~/Desktop$ grep 'durga\>' demo.txt
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
97  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

durga
techdurga

durgasoft@durgasoft:~/Desktop$ cat demo.txt


1234
123456
6789
67543
12
1
durgasoft@durgasoft:~/Desktop$ grep '\<[0-9][0-9][0-9][0-9]\>' demo.txt
1234
6789

It will always search for 4 digit words.

3) Line Patterns (Anchors):


^  Line starts with
$  Line ends with

1) $ grep '^d' demo.txt


It will display all lines starts with d

2) $ grep '^the' demo.txt


It will display all lines starts with the

3) $ grep '^\<the\>' demo.txt


It will display all lines starts with the word 'the'

4) $ grep '^[aeiou]' demo.txt


It will display all lines starts with vowel.

5) $ grep '^[^aeiou]' demo.txt


It will display all lines not starts with vowel.

6) $ grep 't$' demo.txt


It will display all lines ends with t

7) $ grep '[aeiou]$' demo.txt


It will display all lines ends with vowel

8) $ grep '[0-9]$' demo.txt


It will display all lines ends with digit.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
98  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

9) $ grep '^unix$' demo.txt


It will display all lines where total line content should be unix

durgasoft@durgasoft:~/Desktop$ cat > demo.txt


unix
unix software
unix material
material unix
unix unix
durgasoft@durgasoft:~/Desktop$ grep '^unix$' demo.txt
unix

10) $ grep '^....$' demo.txt


It will display all lines where line contains exactly 4 characters.

11) $ grep '^\.' demo.txt


It will display all lines starts with .

12) $ grep '\$$' demo.txt


It will display all lines ends with $

13) $ grep '^$' demo.txt


It will display all blank lines

14) $ grep -v '^$' demo.txt


It will display all lines except blank lines

Q2) How to Delete Blank Lines Present in the given File?


$ grep -v '^$' demo.txt > temp.txt
$ mv temp.txt demo.txt

Note: $ grep -v '^$' demo.txt > demo.txt


The above command won't work
grep: input file ‘demo.txt’ is also the output

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
99  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Additional Patterns supported by only egrep but not grep:


1. (|) It matches any of the string in the given list
$ egrep '(unix|java|oracle)' demo.txt

2. {m}  It matches exact number of preceding character.


$ egrep '[6-9][0-9]{9}' demo.txt
It will search for 10 digit mobile numbers

3. {m,n} The preceding character should match minimum m times and maximum n
times.

$ egrep '[0-9]{1,5}' demo.txt


It will search for lines which contains minimum 1 digit and maximum 5 digit numbers.

4. {m,}  minimum m number of times but no restriction on maximum number

$ egrep '[0-9]{3,}' demo.txt


minimum 3 digits but no restriction on maximum number.

Q3) Write grep Command to retrieve Date Values Present in the


given Input File where Date Values are in the Form
dd-mm-yyyy OR dd/mm/yyyy ?
input.txt
Durga 28-05-1947
Ravi 23/07/1957
shiva 23-09-2015
kljdslgklfjd
dsklfjakdlsfjkl
sdlkfskfjdklsjfdkl

$ egrep -o '\<[0123][0-9][-/][01][0-9][-/][0-9]{4}\>' input.txt

Q4) Write Commands to Count the Number of Directories Present


in the Current Working Directory?
$ ls -l | grep '^d' | wc -l
$ ls -F | grep '/$' | wc -l

Q5) Write Commands to Count the Number of Files Present in the


Current Working Directory?
$ ls -l | grep '^-' | wc -l

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
100  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q6) Write Commands to Count the Number of Link Files Present in


the /etc Directory?
$ ls -F /etc | grep '@$' | wc -l

Q7) Write Command to Display all executable Files Present in /bin


Directory?
$ ls -F /bin | grep '*$'
$ ls -F /bin | grep '*$' | wc –l

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
101  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-21: Cut, Paste and tr


Commands
We can use cut command to extract data from the file.
The file should contain column formatted data, ie tabular data.

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
y
y
n
y
y

2) Display Range of Characters in every Record:


 $cut -c 5-9 emp.dat
It will display 5th to 9th characters in every record

 $cut -c 5- emp.dat
It will display 5th character to last character in every record

 $ cut -c -3 emp.dat
It will display from 1st character to 3rd character in every record.

 $ cut -c 3-5,7-10 emp.dat


It will display 3rd to 5th character and 7th to 10th character in every record.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
102  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

3) Display Specific Column Data:


 $ cut -d '|' -f 3 emp.dat
-d means delimiter (separator). The default delimiter is tab.
-f means field
 It will display 3rd Field (OR Column ) data.

4) Display Range of Columns:


 $ cut -d '|' -f 2-3 emp.dat
It will display 2nd and 3rd Columns data.

 $ cut -d '|' -f 2- emp.dat


It will display from 2nd column to last column data.

 $ cut -d '|' -f -3 emp.dat


It will display from 1st column to 3rd column data.

 $ cut -d '|' -f 1,3,5 emp.dat


It will display 1st, 3rd and 5th column data.

5) Skip specific Column:


 Display all columns except specific column

 $ cut -d '|' --complement -f3 emp.dat


It will display all columns data except 3rd column.

 $ cut -d '|' --complement -f3,5 emp.dat


 $ cut -d '|' --complement -f3-5 emp.dat
 $ cut -d '|' --complement -f3- emp.dat
 $ cut -d '|' --complement -f-5 emp.dat

paste Command:
We can use paste command to join two or more files horizontally by using some delimiter.
Default delimiter is tab.

Syntax: $ paste file1 file2 ...

Eg:
durgasoft@durgasoft:~/Desktop$ cat > subjects.txt
Core Java
Adv Java
Python
Django
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
103  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

UNIX
durgasoft@durgasoft:~/Desktop$ cat > fee.txt
1000
2000
2500
1500
250
durgasoft@durgasoft:~/Desktop$ paste subjects.txt fee.txt
Core Java 1000
Adv Java 2000
Python 2500
Django 1500
UNIX 250

We can specify delimiter explicitly by using -d option.

$ paste -d '-' subjects.txt fee.txt


Core Java-1000
Adv Java-2000
Python -2500
Django-1500
UNIX-250

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.

durgasoft@durgasoft:~/Desktop$ cat > demo.txt


While learning unix not required to eat.

1) $ tr 'aeiou' 'AEIOU' < demo.txt


 It will replace lower case vowels with upper case vowels in demo.txt
 WhIlE lEArnIng UnIx nOt rEqUIrEd tO EAt.

2) $ tr '[a-z]' '[A-Z]' < demo.txt


 Every lower case alphabet symbol will be replaced with upper case alphabet symbol.
 WHILE LEARNING UNIX NOT REQUIRED TO EAT.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
104  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

3) $ tr '[a-zA-Z]' '[A-Za-z]' < demo.txt


 Every lower case character will be replaced with upper case character and every upper
case character will be replaced with lower case character.
 tr '[a-zA-Z]' '[A-Za-z]' < demo.txt > temp.txt

4) $ tr 'aeiou' '7' < demo.txt


To replace every lower case vowel with digit 7.

5) $ tr '|' '\t' < emp.dat


 Replace | symbol with tab in emp.dat
 $ tr '|' ':' < emp.dat

6) $ tr -d 'a' < demo.txt


 -d means delete
 It will delete all occurrence of 'a' in demo.txt
 $ tr -d 'aeiou' < demo.txt
 It will delete all lower case vowels in demo.txt

7) $ tr -s 'a' < demo.txt


 It replaces sequence of a's with a single a.
 -s means squeeze-repeats.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
105  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
106  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

DEVELOPER 'A' CREATED ONE FILE demo.txt

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

Operations related to permissions:


We can perform the following 3 operations.

+  Add a particular permission to user|group|other|all


-  Remove a particular permission to user|group|other|all
=  Assignment a particular permission to user|group|other|all

chmod Command:
chmod means change mode.
We can use chmod command to change file or directory permissions.

Syntax: $ chmod <user_category><operation><permission> file_name/directory_name

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
107  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg: For user add execute permission,for group add write permission,for others remove
read permission
$ chmod u+x,g+w,o-r demo.txt

Note: Only owner and super user (root) can change file permissions.

How to check Permissions of existing File:


By using ls -l command:

durgasoft@durgasoft:~/Desktop$ ls -l
total 0
-rw-r--r-- 1 durgasoft durgasoft 0 Nov 27 21:19 demo.txt

The file permissions are

Total 9 permissions. First 3 are user permissions, next 3 are group permissions and next 3
are others permissions.

user permissions: rw-


user can perform both read and write operations but not execute operation

group permissions: r--


group members can perform only read operation and cannot perform write and
execute operations

others permissions: r--


other members can perform only read operation and cannot perform write and execute
operations.

User Permissions + Group Permissions + Others Permissions


order is important

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
108  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Read permission + Write Permission + Execute Permission


order is important

Eg 1: $ chmod u+x demo.txt


adding execute permission to the user

Eg 2: $ chmod u+w,g+rw,o+r demo.txt


adding write permission to the user
adding read and write permissions to the group
adding read permission to the others

Eg 3: $chmod u+x,g-w,o+w demo.txt


adding execute permission to the user
removing write permission from the group
adding write permission to the others

Eg 4: $ chmod u=rw,g=rw,o=r demo.txt


Now user permissions: rw-
group permission: rw-
others permission: r--

Eg 5: $ chmod a=- demo.txt


Now user permissions: ---
group permission: ---
others permission: ---

Eg 6: $ chmod a=rwx demo.txt


Now user permissions: rwx
group permission: rwx
others permission: rwx

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
109  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

--w-r--r-- 1 durgasoft durgasoft 34 Nov 28 20:56 demo.txt


durgasoft@durgasoft:~/Desktop$ cat demo.txt
cat: demo.txt: Permission denied

Write Permission to the File:


If the file not having write permission, then we cannot modify the content of the file.

durgasoft@durgasoft:~/Desktop$ chmod u-w demo.txt


durgasoft@durgasoft:~/Desktop$ ls -l
total 4
-r--r--r-- 1 durgasoft durgasoft 66 Nov 28 21:04 demo.txt
durgasoft@durgasoft:~/Desktop$

durgasoft@durgasoft:~/Desktop$ cat >> demo.txt


bash: demo.txt: Permission denied
durgasoft@durgasoft:~/Desktop$ chmod u+w demo.txt
durgasoft@durgasoft:~/Desktop$ cat >> demo.txt

Execute Permission to the File:


If the user not has executed permission on any file, then he cannot execute that file as a
program.

durgasoft@durgasoft:~/Desktop$ cat > first.sh


echo "Hello Friends..."
echo "File Permissions is very very important than Sunny"

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
110  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Read Permission to the Directory:


If the user has read permission on any directory, then he can list out the contents of that
directory. i.e he can use ls command.

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$

Write Permission on the Directory:


If the user has write permission on any directory, then he is allowed to modify the content
of that directory. i.e he can add new files and remove existing files.

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
111  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Execute Permission to the Directory:


If the user not has executed permission on any directory, then he is not allowed to enter
into that directory. i.e he cannot use cd command.

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.

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$ ls dir1
ls: cannot access 'dir1/first.sh': Permission denied
ls: cannot access 'dir1/newfile.txt': Permission denied
first.sh newfile.txt
durgasoft@durgasoft:~/Desktop$ touch dir1/demo.txt
touch: cannot touch 'dir1/demo.txt': Permission denied
durgasoft@durgasoft:~/Desktop$ rm dir1/first.sh
rm: cannot remove 'dir1/first.sh': Permission denied

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
112  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

Because of this, Linux is considered as more secured operating system.


Linux follows 2 levels of security.
1st level: login with credentials
2nd level: File and Directory permissions

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.
0  000  No Permission
1  001  Execute Permission
2  010  Write Permission
3  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

It is more easy to remember


5  4+1  r-x
3  2+1  -wx
6  4+2  rw-
etc

1. Write command for the following permissions


For user  Read and write (6)
For group  Write and execute (3)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
113  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

For others  Write (2)

$ chmod 632 demo.txt


durgasoft@durgasoft:~/Desktop$ ls -l demo.txt
-rw--wx-w- 1 durgasoft durgasoft 0 Nov 29 20:57 demo.txt

$ chmod 135 demo.txt


---x-wxr-x 1 durgasoft durgasoft 0 Nov 29 20:57 demo.txt

$ chmod 777 demo.txt


-rwxrwxrwx 1 durgasoft durgasoft 0 Nov 29 20:57 demo.txt

$ 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
0022

First 0 is sticky bit mostly used in admin related activities. We have to consider only last 3
digits as umask value.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
114  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

Default permissions to the directory= 777 - umask value


=777-022
=755 (user  r&w&x, group  r&x, others  r&x)

$ mkdir dir1
$ ls -l
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 29 21:21 dir1

Based on our requirement we can set our own umask values.


durgasoft@durgasoft:~/Desktop$ umask 002
durgasoft@durgasoft:~/Desktop$ touch file2.txt
durgasoft@durgasoft:~/Desktop$ ls -l file2.txt
-rw-rw-r-- 1 durgasoft durgasoft 0 Nov 29 21:24 file2.txt
durgasoft@durgasoft:~/Desktop$ mkdir dir2
durgasoft@durgasoft:~/Desktop$ ls -l
drwxrwxr-x 2 durgasoft durgasoft 4096 Nov 29 21:24 dir2

Q1) For Newly created Files Default Permissions should be 444.


Then what should be umask Value?
Ans: 222
Everyone has only read access.

Note: The most commonly used umask values are: 022


002
077
007
Eg:
durgasoft@durgasoft:~/Desktop$ umask 077
durgasoft@durgasoft:~/Desktop$ umask
0077
durgasoft@durgasoft:~/Desktop$ touch file3.txt
durgasoft@durgasoft:~/Desktop$ ls -l file3.txt
-rw------- 1 durgasoft durgasoft 0 Nov 29 21:30 file3.txt
Negative values won't be considered in linux.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
115  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

chown Command:
chown means change owner.
Only root user can perform this activity.

# chown root demo.txt


Now the owner of demo.txt is root.

chgrp Command:
chgrp means change group.
Only root user can perform this activity.

# chgrp root demo.txt


Now the demo.txt belongs to root group.

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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
116  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

echo "Hello Friends"


echo "Hello Friends"
echo "Durgasoft group member can perform write"
durgasoft@durgasoft:~/Desktop$ cat >> demo.txt
bash: demo.txt: Permission denied
durgasoft@durgasoft:~/Desktop$ ./demo.txt
bash: ./demo.txt: Permission denied

Group Permissions:
durgasoft durgasoft

-rwxr--r-- 1 root durgasoft 46 Nov 30 20:11 demo.txt

r-- group members can perform only read operation


durgasoft@durgasoft:~/Desktop$ cat demo.txt
echo "easy but listen"
echo "easy but listen"
durgasoft@durgasoft:~/Desktop$ cat >> demo.txt
bash: demo.txt: Permission denied
durgasoft@durgasoft:~/Desktop$ ./demo.txt
bash: ./demo.txt: Permission denied
durgasoft@durgasoft:~/Desktop$

-rwxrw-r-- 1 root durgasoft 46 Nov 30 20:11 demo.txt


rw-

Others Permissions:
-rwxrwxr-- 1 root root 114 Nov 30 20:22 demo.txt

durgasoft will become others


r-- only read permission

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
117  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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

echo "This is my first shell script"


mkdir dir{1..6}
echo "six directories got created"
date
cal

$ chmod u+x first.sh


$ ./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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
118  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

2) Working with vi Editor:


vi means visual editor.
We can use vi to create new files and to edit content of the existing files.

$ 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.

How to edit the File:


There are 3 types of modes in file editing

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.

2) Insert Mode OR Input Mode:


 In this mode, we can modify file data. We can insert/append new data.
 From insert mode, we can enter into command mode by using <Esc> key.

3) Exit Mode:
 To quit from the editor.
 From the command mode we have to press: then we can enter into exit mode.

How to Insert and Append Data:


A  To Append data at the end of the line
I  To Insert data at the beginning of the line
a  To append data to the right side of the cursor position (Just after the cursor position)
i  To insert data to the left side of the cursor position (Just before the cursor position)

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
119  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

How to Delete Data:


We can delete data either by character wise or by word wise or by line wise.

deletion character wise:

x  To delete a single character (del key)


3x  To delete 3 characters. Instead of 3, we can pass any number.
X  To delete previous character (backspace key)
3X  To delete last 3 previous characters

Deletion Words wise:


dw  To delete current word.
3dw  To delete 3 words

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.

How to Replace Data:


r  Replace current character.
R  To replace multiple characters from the current position.
S OR cc  To replace a single line

Opening New Lines to Insert Data:


O To open a line above the cursor position.(i.e before current line)
o  To open a line below the cursor position (i.e after current line)

Copy and Paste Data:


yy  To Copy a Line (yanking)
3yy  To copy 3 lines
yw  To copy a word
3yw  To copy 3 words
y$  To copy from current cursor position to end of line.
y^  To copy from beginning of the line to current cursor position.
p  Paste above the cursor position
P  Paste below the cursor position

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
120  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Cursor Navigation Commands:


k  Top Arrow
j  Bottom Arrow
l  Right Arrow
h  Left Arrow
3k  3 Times Top Arrow
3j  3 Times Bottom Arrow
3l  3 Times Right Arrow
3h  3 Times Left Arrow
$  End of the Current Line (End Key)
^  Beginning of the Current Line (Home Key)
H  Beginning of the Current Page
M  Middle of the Current Page
L  End of the Current Page

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.

G  Move to last line (ie end of the file)

at exit mode
:1  To go to 1st line
:7  To go to 7th line

ctrl+f  One Page Forward (Page Down)


ctrl+b  One Page Backward( Page Up)

Note: If we want to perform undo previous operation then we should use 'u'
u  Means undo previous operation

Exit Mode Commands:


:w  Save File Data
:wq  Save and Quit from the Editor
:q  Quit Editor
:q!  Force Quit. If we perform any changes those will be discarded.

:set nu  To set line numbers in the editor


:set nonu  To remove line numbers
:n  Place the cursor to the nth line
:$  Place the cursor to the last line
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
121  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

:!<unix_command>  To execute any command

Eg:
:!date  To check system date
:!cal  To check calander

Note: vi +7 demo.txt
open demo.txt and enter into 7th line

3) Working with nano Editor:


 It is command line editor.
 It can be used to create new files and edit content of existing files.
 It is almost like notepad.

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

ctrl+w (F6) Search forward for a string or a regular expression


ctrl+\ (M-R) Replace a string or a regular expression
ctrl+k (F9) Cut the current line and store it in the cutbuffer
ctrl+u (F10) Uncut from the cutbuffer into the current line

But main important options:


ctrl+o  To save content
ctrl+x  To quit from the editor

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
122  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Part-2
Shell Scripting

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
123  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Agenda
Topic-24: Shell Scripting / Shell Programming:

Topic-25: What is shell script, Sha-Bang and First Script

Topic-26: Shell Variables

Topic-27: Variable Substitution and Command Substitution

Topic-28: Command Line Arguments

Topic-29: How to read dynamic data from the user

Topic-30: Operators

Topic-31: Control Statements

Topic-32: Arrays

Topic-33: Shell Script Functions

Topic-34: Project on Shell Programming

Topic-35: Stream Editor(SED)

Topic-36: AWK Programming

Topic-37: Project on awk programming

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
124  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-24: What is Shell and


Types of Shells
What is Shell?

1) Shell is responsible to read commands/applications provided by user.


2) Shell will check whether command is valid or not and whether it is properly used or
not. If everything is proper then shell interpretes (converts) that command into kernel
understandable form. That interpreted command will be handover to kernel.
3) Kernel is responsible to execute that command with the help of hardware.

Shell acts as interface between user and kernel.


shell+kernel is nothing but operating system.

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
125  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

How to Check Default Shell in our System?


$ echo $0
bash
$ echo $SHELL
/bin/bash

We can also check the default shell information inside /etc/passwd file
$ cat /etc/passwd

durgasoft:x:1000:1000:durgasoft,,,:/home/durgasoft:/bin/bash

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
126  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

How to check all available Shells in our System?


/etc/shells file contains all available shells information.

$ cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/bin/rbash
/bin/dash

How to Switch to other Shells?


Based on our requirement we can switch from one shell to another shell.

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
127  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-25: What is Shell Script, Sha-Bang


and First Script
What is Shell Script:
A sequence of commands saved to a file and this file is nothing but shell script.

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.

Best suitable for automated tasks.

How to write and run Shell Script:


Step - 1: Write script

demo.sh:
echo "Welcome to shell script"
date
cal

Step - 2: Provide execute permissions to the script:


$ chmod a+x demo.sh

Step - 3: Run the script


We can run the script in multiple ways

$ /bin/bash ./demo.sh
$ bash ./demo.sh
$ /bin/bash /home/durgasoft/scripts/demo.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

nd
DURGASOFT, # 202, 2 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

#! /bin/bash  It means the script should be executed by bash


#! /bin/sh  It means the script should be executed by Bourne Shell
#! /usr/bin/python3  It means the script should be executed by Python3 interpreter

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.

Q1) Write a Python Script and execute without shabang and


with shabang?
test.py
#! /usr/bin/python3
import random
name = input("Enter Your Name:")
l =["Sunny","Katrina","Kareena","Mallika","Malaika"]
print("Hello:",name)
print("Congratulations..You are going to marry:",random.choice(l))

Without Shabang:
$ python3 ./test.py
$ python3 /home/durgasoft/scripts/test.py

With Shabang:
$ ./test.py
$ /home/durgasoft/scripts/test.py

Q2) Consider the folloiwng Script:


demo.sh
#! /bin/rm
echo "It is beautiful script"

If we execute this script what will happend?


$ ./demo.sh
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
129  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

It is equivalent to
$ rm ./demo.sh
demo.sh will be removed as this script executed by rm command.

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

Provide execute permissions for this script


$ chmod a+x date.sh
$./date.sh

Q4) How to Run Our Script from any where in our System?
 For any command or script, by default shell will check locations specified by PATH
variable.

 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

durgasoft@durgasoft:~/scripts$ echo $PATH


/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:
/snap/bin:/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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
130  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: This way of setting PATH variable is applicable only for current session. Once we
close terminal then automatically these changes will be lost.

2) Setting PATH permanently at User Level:


 In our user home directory there is a file named with .bashrc. This file will be executed
every time automatically whenever we open the terminal. If we define PATH variable
in this file then that PATH value will become permanent and we are not required to set
every time.

 Add the following line at bottom of this file

 export PATH=$PATH:/home/durgasoft/scripts

Q5) What is the meaning of Startup File?


 .bashrc is the startup file and will be executed automatically at the time of
terminal starting.
 Hence if we want to perform any activity while starting the terminal we have to
define that activity in this file.
 eg: creating aliases and updating PATH variable value etc

Q6) What is meant by logout File?


 .bash_logout is logout file and will be executed automatically at the time of
terminal exit.
 Hence if we want to perform any activity at terminal exit, then we have to define
that activity inside this file.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
131  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

All variables are divided into 2 types


1) Environment variables / predefined variables
2) User defined variables

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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
132  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

LANG=en_IN
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
PS1='\[\e]0;\u@\h:
\w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[0
1;34m\]\w\[\033[00m\]\$ '
PWD=/home/durgasoft
SHELL=/bin/bash

How to Change Prompt:


Internally PS1 Environment variable is responsible to display terminal prompt. By
reassigning the value we can change prompt.

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
drwxr-xr-x 2 durgasoft durgasoft 4096 Dec 5 18:04 Desktop
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 21 17:06 Documents
drwxr-xr-x 2 durgasoft durgasoft 4096 Nov 21 17:06 Downloads

Demo Script to Use some Environment Variables:


env.sh
#! /bin/bash
echo "User Name: $USER"
echo "User Home Directory: $HOME"
echo "Default Shell Name: $SHELL"
echo "PATH: $PATH"

$chmod 755 env.sh


$./env.sh
User Name: durgasoft
User Home Directory: /home/durgasoft
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
133  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

2) User defined Variables:


Based on our programming requirement, we can define our own variables also.

durgasoft@durgasoft:~/scripts$ GUEST=Dhoni
durgasoft@durgasoft:~/scripts$ echo "Hello $GUEST You are my Hero"
Hello Dhoni You are my Hero

Rules to define Variables:


1) It is recommended to use only UPPER CASE characters.
2) If variable contains multiple words, then these words should be separated with _
symbol.
3) Variable names should not starts with digit.
durgasoft@durgasoft:~/scripts$ 123A=40
123A=40: command not found
4) We should not use special symbols like -,@,# etc

How to define Readonly Variables:


We can define read only variables by using readonly keyword.
$A=100
$readonly A
$A=300
bash: A: readonly variable

If the variable is readonly then we cannot perform reassignment for that variable.It will
become constant.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
134  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Variable Scopes:
There are 3 scopes available for variables.

1) Session Scope
2) User Scope
3) System Scope

1) 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.

We have to declare these variables inside /etc/profile file.


But to edit this file compulsory root permissions must be required.

$ sudo gedit /etc/profile

...
export NAME=DURGA
export COURSE=PYTHON

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
135  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-27: Variable Substitution and


Command Substitution
Variable Substitution:
Accessing the value of a variable by using $ symbol is called variable substitution.

Syntax:
$variablename
${variablename}

Recommended to use ${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

Q1) Consider the following variable declaration NAME="durga"


Which of the following is valid way to print value of NAME?
A) echo NAME
B) echo $NAME
C) echo '$NAME'
D) echo "$NAME"

Ans: B, D

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
136  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: If we use single quotes then variable substitution won't be happend. But we can
use double quotes.

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
137  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg 4:
durgasoft@durgasoft:~/scripts$ echo "My Current Working Directory: `pwd` "
My Current Working Directory: /home/durgasoft/scripts
durgasoft@durgasoft:~/scripts$ echo "My Current Working Directory: $(pwd) "
My Current Working Directory: /home/durgasoft/scripts

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
138  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

$ ./test.sh learning linux is very easy

The command line arguments are learning, linux, is, very, easy.

Inside scritp we can access command line arguments as follows:

$#  Number of Arguments (5)


$0  Script Name (./test.sh)
$1  1st Argument (learning)
$2  2nd Argument (linux)
$3  3rd Argument (is)
$4  4th Argument (very)
$5  5th Argument (easy)
$*  All Arguments (learning Linux is very easy)
$@ All Arguments (learning Linux is very easy)
$?  Represents exit code of previously executed command or script.

Eg: test.sh
#! /bin/bash
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: $*"

durgasoft@durgasoft:~/scripts$ ./test.sh learning linux is very easy


Number of arguments: 5
Script Name: ./test.sh
First argument: learning
Second argument: linux
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
139  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Third argument: is
Fourth argument: very
Fifth argument: easy
Total arguments: learning linux is very easy

Difference between $@ and $*:


$@  All command line arguments with space separator
"$1" "$2" "$3" ...
$*  All command line arguments as single string
"$1c$2c$3c.."
Where c is the first character of the Internal Field Separator (IFS).
The default first character is space.

How to Check Default IFS:


$ set | grep "IFS"
IFS=$' \t\n'

How to Change IFS:


#! /bin/bash

IFS="-"

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: $@"
echo "Total arguments: $*"

durgasoft@durgasoft:~/scripts$ test.sh learning unix is very easy


Number of arguments: 5
Script Name: /home/durgasoft/scripts/test.sh
First argument: learning
Second argument: unix
Third argument: is
Fourth argument: very
Fifth argument: easy
Total arguments: learning unix is very easy
Total arguments: learning-unix-is-very-easy

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
140  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: The main purpose of command line arguments is to customize behaviour of the
script.

test.sh
#! /bin/bash
l=$(echo -n "DURGA"| wc -c)
echo "The Length of given String: $l"

This script will work only for string: DURGA

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

Q1) Write Script to Create Log File with Timestamp


test.sh
#! /bin/bash
timestamp=$(date +%d_%m_%Y_%H_%M_%S)
echo "This is data to log file" >> ${timestamp}.log
echo "This is extra data to log file" >> ${timestamp}.log
date >> ${timestamp}.log
echo >> ${timestamp}.log
echo "Data Written to log file successfully"

If we execute this script, every time a new file will be created.


If we take
timestamp=$(date +%d_%m_%Y_%H_%M)
Then log file will be created for every new minute.

For every hour if want a new log file: timestamp=$(date +%d_%m_%Y_%H)


For every day if want a new log file: timestamp=$(date +%d_%m_%Y)

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
141  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-29: How to Read Dynamic Data


from the User
By using read keyword we can read dynamic data from the end user.

Without Prompt Message:


durgasoft@durgasoft:~/scripts$ read a b
100 200
durgasoft@durgasoft:~/scripts$ echo "The values of a and b are:$a and $b"
The values of a and b are:100 and 200

With Prompt Message:


Approach-1

test.sh
#! /bin/bash
echo "Enter A Value:"
read A

echo "Enter B Value:"


read B

echo "A Value: $A"


echo "B Value: $B"

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
142  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

echo -n "Enter B Value:"


read B
echo "A Value: $A"
echo "B Value: $B"
durgasoft@durgasoft:~/scripts$ test.sh
Enter A Value:100
Enter B Value:200
A Value: 100
B Value: 200

Approach-2
#! /bin/bash
read -p "Enter A Value:" A
read -p "Enter B Value:" B

echo "A Value: $A"


echo "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

echo "$user thanks for your information"

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
echo "Hello $user , thanks for your information"

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
143  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

durgasoft@durgasoft:~/scripts$ test.sh
Enter User Name:Durga
Enter Password:
Hello Durga , thanks for your information

Q2) Write a Script to Read Student Data and display to the


Console for Confirmation?
#! /bin/bash
read -p "Enter Student Name:" name
read -p "Enter Student RollNo:" rollno
read -p "Enter Student Age:" age
read -p "Enter Student Marks:" marks
echo "Please confirm your details"
echo "------------------------------------------------"
echo "Student Name: $name"
echo "Student Rollno: $rollno"
echo "Student Age: $age"
echo "Student Marks: $marks"

durgasoft@durgasoft:~/scripts$ test.sh
Enter Student Name:Durga
Enter Student RollNo:101
Enter Student Age:40
Enter Student Marks:89
Please confirm your details
------------------------------------------------
Student Name: Durga
Student Rollno: 101
Student Age: 40
Student Marks: 89

Q3) Write a Script to Read Employee Details and Save to


emp.txt File?
#! /bin/bash
read -p "Enter Employee Number:" eno
read -p "Enter Employee Name:" ename
read -p "Enter Employee Salary:" esal
read -p "Enter Employee Address:" eaddr

echo "Below details are saved to the file"


echo "$eno:$ename:$esal:$eaddr"
echo "$eno:$ename:$esal:$eaddr" >> emp.txt

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
144  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

durgasoft@durgasoft:~/scripts$ test.sh
Enter Employee Number:100
Enter Employee Name:Sunny
Enter Employee Salary:1000
Enter Employee Address:Mumbai
Below details are saved to the file
100:Sunny:1000:Mumbai
durgasoft@durgasoft:~/scripts$ test.sh
Enter Employee Number:200
Enter Employee Name:Bunny
Enter Employee Salary:2000
Enter Employee Address:Hyderabad
Below details are saved to the file
200:Bunny:2000:Hyderabad
durgasoft@durgasoft:~/scripts$ test.sh
Enter Employee Number:300
Enter Employee Name:Chinny
Enter Employee Salary:3000
Enter Employee Address:Chennai
Below details are saved to the file
300:Chinny:3000:Chennai
durgasoft@durgasoft:~/scripts$
durgasoft@durgasoft:~/scripts$ cat emp.txt
100:Sunny:1000:Mumbai
200:Bunny:2000:Hyderabad
300:Chinny:3000:Chennai

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"

durgasoft@durgasoft:~/scripts$ test.sh
Enter any string to find length:apple
Length of apple : 5
durgasoft@durgasoft:~/scripts$ test.sh
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
145  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Enter any string to find length:durgasoftwaresolutions


Length of durgasoftwaresolutions : 22

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

sort -u $fname > temp.txt


mv temp.txt $fname
echo "In $fname all duplicate lines deleted"

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
146  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-30: Operators
1) Arithmetic Operators
+  Addition
-  Substraction
*  Multiplication (we should use \* as it is wild card character)
/  Division
%  Modulo Operator

Relational Operators: (Numeric Comparison Operators)


-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal to
-eq  Is equal to
-ne Not equal to

These operators return boolean value (true/false)

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.

How to perform Mathematical Operations:


There are multiple ways

1) By using expr keyword


2) By using let keyword
3) By using (())
4) By using []

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
147  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

1) By using expr Keyword:


expr means expression and it is a keyword.

#! /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"

Note: While using expr keyword, $ symbol is mandatory.


Space must be required before and after + symbol.

2) By using let Keyword:


let sum=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"

Here also space and $ symbol, both are optional.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
148  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Note: All the above 4 approaches will work only for integral arithmetic
(only for integer numbers).
If we want to perform floating point arithmetic then we should use bc command.

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

Note: bc can perform both integral and floating point arithmetic.

Script for floating Point Arithmetic:


#! /bin/bash

read -p "Enter First Number:" a


read -p "Enter Second Number:" b

sum=$( echo $a+$b | bc)


echo "The Sum:$sum"

echo "The Difference: $( echo $a-$b | bc)"


echo "The Product: $( echo $a*$b | bc)"

Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter First Number:10.5
Enter Second Number:5.3
The Sum:15.8
The Difference: 5.2
The Product: 55.6

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
149  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q1) Write a Script to Read 2 Integer Numbers and Print


Sum?
#! /bin/bash

read -p "Enter First Number:" a


read -p "Enter Second Number:" b
sum=$[a+b]
echo "The Sum:$sum"

Q2) Write a Script to Read 4 Digit Integer Number and Print


the Sum of Digits Present in that Number?
#! /bin/bash

read -p "Enter Any 4-digit Integer Number:" n

a=$( echo $n | cut -c 1)


b=$( echo $n | cut -c 2)
c=$( echo $n | cut -c 3)
d=$( echo $n | cut -c 4)

echo "The Sum of 4 digits : $[a+b+c+d]"

durgasoft@durgasoft:~/scripts$ test.sh
Enter Any 4-digit Integer Number:1234
The Sum of 4 digits : 10
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any 4-digit Integer Number:3456
The Sum of 4 digits : 18

Q3) Write a Script to Read Employee Monthly Salary and


Print his Bonus. The Bonus should be 25% of Annual Salary
#! /bin/bash

read -p "Enter Employee Monthly Salary:" salary

annual_salary=$[salary*12]
bonus=$[annual_salary*25/100]
echo "The Bonus:$bonus"

durgasoft@durgasoft:~/scripts$ test.sh
Enter Employee Monthly Salary:10000
The Bonus:30000
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
150  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Topic-31: Control Statements


1) if statement
2) case statement
3) while loop
4) for loop
5) until loop
6) break
7) continue
8) exit

1) 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

read -p "Enter Your Name:" name

if [ $name = "sunny" ]
then
echo "Hello Sunny Very Good Evening"
fi
echo "How are you"

durgasoft@durgasoft:~/scripts$ test.sh
Enter Your Name:durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
151  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 condition is true
else
action if condition is false
fi

3) Nested if:
if [ condition ]
then
.........
.........
if [ condition ]
then
.........
.........
else
........
fi
.....
else
......
fi

4) ladder -if:
if [condition]
then
action-1
elif [ condition ]
then
action-2
elif [ condition ]
then
action-3
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
152  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

else
default action
fi

Q2) Write a Script to find Greater of 2 Numbers?


#! /bin/bash

read -p "Enter First Number:" a


read -p "Enter Second Number:" b

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

Q3) Write a Script to Check whether Numbers OR Equal OR Not.


If the Numbers are not Equal then Print Greater Number?
#! /bin/bash

read -p "Enter First Number:" a


read -p "Enter Second Number:" b

if [ $a -eq $b ]
then
echo "Both Numbers are equal"
elif [ $a -gt $b ]
then
echo "First Number is greater than Second Number"
else
echo "First Number is less than Second Number"
fi
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
153  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q4) Write a Script to find Greater of 3 Numbers?


1st Way:
#! /bin/bash

read -p "Enter First Number:" a


read -p "Enter Second Number:" b
read -p "Enter Third Number:" c

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

read -p "Enter First Number:" a


read -p "Enter Second Number:" b
read -p "Enter Third Number:" c

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

WAS to check whether student is pass or fail based on given 3 subjects marks.
In any subject if marks less than 35 then status is fail.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
154  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

1st Way:
#! /bin/bash

read -p "Enter First Subject Marks:" a


read -p "Enter Second Subject Marks:" b
read -p "Enter Third Subject Marks:" c

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

read -p "Enter First Subject Marks:" a


read -p "Enter Second Subject Marks:" b
read -p "Enter Third Subject Marks:" c

if [ $a -ge 35 -a $b -ge 35 -a $c -ge 35 ]


then
echo "Result is Pass"
else
echo "Result is Fail"
fi

The Funniest Example with if-else


#! /bin/bash

read -p "Enter Your Favourite Brand:" brand

if [ $brand = "KF" ]
then
echo "It is Childrens Brand"

elif [ $brand = "KO" ]


nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
155  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

then
echo "It is not that much Kick"

elif [ $brand = "RC" ]


then
echo "It is too light"

elif [ $brand = "FO" ]


then
echo "Buy One Get One FREE"
else
echo "Other Brands are not recommended"
fi

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 Codes/ Status Codes:


Every command and script return some value after execution, which indicates that
whether it is successfully executed or not. This return value is called exit code or status
code.

We can find exit code by using "$?".

zero means command/script executed successfully.


non-zero means command/scrit not executed successfully.

durgasoft@durgasoft:~/scripts$ echo "Hello Friends"


Hello Friends
durgasoft@durgasoft:~/scripts$ echo "$?"
0
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
156  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

durgasoft@durgasoft:~/scripts$ rm sdfjkslajfdksajfjdsakjfdksajfkd
rm: cannot remove 'sdfjkslajfdksajfjdsakjfdksajfkd': No such file or
directory
durgasoft@durgasoft:~/scripts$ echo "$?"
1

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

nd
DURGASOFT, # 202, 2 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

Q6) Write a Script that Reads an Integer Number and Check


whether the given Number is +ve Number OR -ve Number?
#! /bin/bash

read -p "Enter integer number to check:" n


if [ $n -gt 0 ]; then
echo "$n is +ve number"
else
echo "$n is -ve number"
fi

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

Note: If we want to take then in the same line then we should use ;
if [ $n -gt 0 ]; then
The advantage is we can reduce the number of lines.

Q7) Write a Script that Reads an Integer Number and Checks


whether it is Even Number OR not?
#! /bin/bash

read -p "Enter integer number to check:" n


if [ $[n%2] -eq 0 ]; then
echo "$n is even number"
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
158  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

else
echo "$n is odd number"
fi

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

Q8) Write a Script that Reads an Integer Number and Checks


whether it is 3 Digit Number OR not?
#! /bin/bash

read -p "Enter integer number to check:" n

if [ $n -ge 100 -a $n -le 999 ]; then


echo "$n is 3-dgit number"
else
echo "$n is not 3-digit number"
fi

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

File Test Options:


-e  Returns true if file/directory exists
-s  Returns true if the file is non-empty
-f  Returns true if the file is a regular file
-d  Returns true if the file is a directory
-l  Returns true if the file is link file
-b  Returns true if the file is block special file
-c  Returns true if the file is character special file
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
159  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

-r  Returns true if current user has read permission on the file


-w  Returns true if current user has write permission on the file
-x  Returns true if current user has execute permission on the file
-o  Returns true if current user is owner of the file.
file1 -ot file2  Returns true if file1 is older than file2 (last modified time)
file1 -nt file2  Returns true if file1 is newer than file2(last modified time)

Eg 1: Script to Test whether the given File Exists OR not?


#! /bin/bash

read -p "Enter File Name to test:" fname

if [ -e $fname ]
then
echo "$fname exists"
else
echo "$fname not exists"
fi

Eg 2: Script to Test whether the given File is Regular File OR


Directory?
#! /bin/bash

read -p "Enter File Name to test:" fname

if [ -e $fname ]; then
if [ -f $fname ]; then
echo "It is regular file"
elif [ -d $fname ]; then
echo "It is Directory file"
else
echo "It is special file"
fi
else
echo "$fname does not exist"
fi

Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to test:a.txt
It is regular file
durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to test:dir1
It is Directory file
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
160  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to test:dddddd
dddddd does not exist
durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to test:/bin
It is Directory file
durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to test:/dev/vcsa3
It is special file

Write a Script that Reads a File Name and Display its


Content to the Terminal?
#! /bin/bash

read -p "Enter File Name to test:" fname

if [ -e $fname ]; then
if [ -f $fname ]; then
if [ -r $fname ]; then
cat $fname
else
echo "User not having Read permission"
fi
else
echo "It is not a regular file"
fi
else
echo "$fname does not exist"
fi

Q9) Write a Script that Reads File Name and Check whether
it is Empty File OR not?
#! /bin/bash

read -p "Enter File Name to test:" fname

if [ -e $fname ]; then
if [ -f $fname ]; then
if [ -s $fname ]; then
echo "$fname is not empty file"
else
echo "$fname is empty file"
fi
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
161  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

else
echo "It is not a regular file"
fi
else
echo "$fname does not exist"
fi

Q10) Write a Script that Accepts 2 File Names and Check


whether both Files having same Content OR not?
#! /bin/bash

read -p "Enter First File Name: " fname1


read -p "Enter Second File Name: " fname2

result=$(cmp $fname1 $fname2)


if [ -z "$result" ]; then
echo "The given 2 files having same content"
else
echo "The given 2 files having different content"
fi

Note:
-z is string comparison option.
returns True if the string is empty.

Q11) Write a Script that Accepts a File Name and Display


User Permissions?
#! /bin/bash

read -p "Enter First File Name: " fname

READ=NO
WRITE=NO
EXECUTE=NO

if [ -r $fname ]; then
READ=YES
fi

if [ -w $fname ]; then
WRITE=YES
fi

nd
DURGASOFT, # 202, 2 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

echo "User Permissions Summary"


echo "-------------------------"
echo "Read Permission: $READ"
echo "Write Permission: $WRITE"
echo "Execute Permission: $EXECUTE"

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

read -p "Enter file/directory name to delete:" fname


if [ -e $fname ]; then
rm -r $fname
echo "$fname removed successfully"
else
echo "$fname does not exist"
fi

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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
163  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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.

String Test Options:


1) str1 = str2  Returns true if both strings are same
2) str1 != str2  Returns true if both strings are different
3) -z str  Returns true if the string is empty
4) -n str  Returns true if the string is not empty
5) str1 > str2  Returns true if the str1 is alphabetically greater than str2
5) str1 < str2  Returns true if the str1 is alphabetically less than str2

Demo Program For String Comparison:


#! /bin/bash

read -p "Enter First String:" str1


read -p "Enter Second String:" str2

if [ $str1 = $str2 ]; then


echo "Both strings are equal"

elif [ $str1 \< $str2 ]; then


echo "$str1 is less than $str2"
else
echo "$str1 is greater than $str2"
fi

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@durgasoft:~/scripts$ test.sh
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
164  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
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)

if [ $user != "root" ]; then


echo "Current user not root user and hence exiting"
exit 1
fi

echo "The Five Current Running Processes information"


echo "=============================================="
ps -ef | head -5

durgasoft@durgasoft:~/scripts$ test.sh
Current user not root user and hence exiting
durgasoft@durgasoft:~/scripts$ sudo -i
[sudo] password for durgasoft:
root@durgasoft:~# whoami
root
root@durgasoft:~# test.sh
test.sh: command not found
root@durgasoft:~# pwd
/root
root@durgasoft:~# /home/durgasoft/scripts/test.sh

The 5 Current Running Processes Information


UID PID PPID C STIME TTY TIME CMD
root 1 0 0 19:32 ? 00:00:03 /sbin/init splash
root 2 0 0 19:32 ? 00:00:00 [kthreadd]
root 3 2 0 19:32 ? 00:00:00 [rcu_gp]
root 4 2 0 19:32 ? 00:00:00 [rcu_par_gp]

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
165  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q14) Write a Script to Test whether the given String is Empty OR


not? If it is not Empty then Print its Length
#! /bin/bash

read -p "Enter Any String to test:" str

if [ -z $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.

 To handle such type of requirements we should go for case statement.

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
166  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg 1: Write a script to read a number from 0 to 9 and print equivalent English word?
#! /bin/bash

read -p "Enter Any digit from 0 to 9:" n

case $n in
0) echo "ZERO"
;;
1) 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

Q15) Write a Script that Reads Favourite Brand and Prints


corresponding Meaningful Message?
#! /bin/bash

read -p "Enter Your Favourite Brand: " brand

case $brand in
"KF")
echo "It is childrens brand"
;;
"KO")
echo "It is not that much kick"
;;

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
167  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

"RC")
echo "It is too light"
;;
"FO")
echo "Buy one get one FREE"
;;
*)
echo "Other brands are not recommended"
esac

Q16) Write a Script that Accepts a Single Character and Check whether the
given Character is Alphabet OR Digit OR Special Character?
#! /bin/bash

read -p "Enter Any Character to check: " ch

case $ch in
[a-zA-Z])
echo "It is an Alphabet symbol"
;;
[0-9])
echo "It is a Digit"
;;
[^a-zA-Z0-9])
echo "It is a Special Symbol"
;;
*)
echo "Enter only one character"
esac

durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: a
It is an Alphabet symbol
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: 8
It is a Digit
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: $
It is a Special Symbol
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: durga
Enter only one character

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
168  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

read -p "Enter Any Character to check: " ch

case $ch in
[^a-zA-Z0-9])
echo "It is a Special Character"
;;
[0-9])
echo "It is a Digit"
;;
[aeiouAEIOU])
echo "It is a Vowel"
;;
[^aeiouAEIOU])
echo "It is a Consonent"
;;
*)
echo "Enter only one character"
esac

durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: a
It is a Vowel
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: s
It is a Consonent
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: 7
It is a Digit
durgasoft@durgasoft:~/scripts$ test.sh
Enter Any Character to check: $
It is a Special Character

Q18) Write a Script that performs File Operations based on


provided Option?
A  Display Content
B  Append Content
C  Overwrite Content
D  Delete Content

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
169  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

echo "The content of the file is:"


echo "---------------------------"
cat abc.txt
fi
;;
B)
read -p "Provide your data to append:" data
echo $data >> abc.txt
echo "Data Appended"
;;
C)
read -p "Provide your data to overwrite:" data
echo $data > abc.txt
echo "Old data Overwritten with new data "
;;
D)
cat /dev/null > abc.txt
echo "Deleted the content of the file"
;;
*)
echo "Choose only A|B|C|D. Execute Again"
esac

Q19) Write a Script that Reads 2 Integer Numbers and perform


required Mathematical Operation based on provided Option?
1  Addition Operation
2  Subtraction Operation
3  Multiplication Operation
4  Division Operation
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
170  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

#! /bin/bash

read -p "Enter First Number: " n1


read -p "Enter Second Number: " n2
echo ""
echo "1 --> Addition Operation"
echo "2 --> Subtraction Operation"
echo "3 --> Multiplication Operation"
echo "4 --> Division Operation"
read -p "Choose Your Option 1|2|3|4: " option

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

Iterative Statements:
If we want to execute a group of commands multiple times then we should go for iterative
statements.

There are 3 types of iterative statements

1) while loop
2) until loop
3) for loop

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
171  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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.

Q1) Write a Script to Print Numbers from 1 to 10


#! /bin/bash

i=1

while [ $i -le 10 ]
do
echo $i
let i++
done

Q2) Write a Script to generate Numbers until Limit which is


provided by End User?
#! /bin/bash

read -p "Enter Limit:" n


i=1

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.

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
172  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Eg:
sleep 2
sleep 3
sleep 0.5

Q3) Write a Script to find the Sum of First n Integers, where n is


provided by End User?
#! /bin/bash

read -p "Enter n value:" n

i=1
sum=0
while [ $i -le $n ]
do
let sum=sum+i
let i++
done

echo "The Sum of first $n numbers: $sum"

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

Q4) Write a Script to Display Timer (Digital Timer)?


#! /bin/bash

while [ true ]
do
clear
printf "\n\n\n\n\n\n\t\t\t\t$(date +%H:%M:%S)"
sleep 1
done

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173  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/bash

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
done

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
174  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

Output:
1
3
5
7
9

Write a Script to Read File Name and Display its Content?


#! /bin/bash

while [ true ]
do
read -p "Enter File Name to Display content: " fname

# Checking whether the file exists or not and whether regular file or not
if [ -f $fname ]; then
echo "The content of $fname :"
echo "----------------------"
cat $fname
else
echo "$fname does not exist"
fi

read -p "Do you want to display content of another file [Yes|No]:" option
case $option in
[yY]|[Yy][eE][sS])
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
175  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

continue
;;
[nN]|[nN][oO])
break
;;
esac
done
echo "Thanks for using application"

Output:
durgasoft@durgasoft:~/scripts$ test.sh
Enter File Name to Display content: abc.txt

The content of abc.txt:


Java
Python
Do you want to display content of another file [Yes|No]:y
Enter File Name to Display content: a.txt

The content of a.txt:


Tue Dec 10 17:00:48 IST 2019
Do you want to display content of another file [Yes|No]:YES
Enter File Name to Display content: b.txt

The content of b.txt:


December 2019
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Do you want to display content of another file [Yes|No]:Y


Enter File Name to Display content: durga.txt
durga.txt does not exist
Do you want to display content of another file [Yes|No]:N
Thanks for using application

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
176  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Write a Script that Reads a String as Input and find its Reverse?
Write a Script that performs Reverse of given String?
#! /bin/bash

read -p "Enter any string to find reverse: " str

len=$( echo -n $str | wc -c )


output=""

while [ $len -gt 0 ]


do
ch=$( echo -n $str | cut -c $len)
output=$output$ch
let len--
done
echo "The Original String: $str"
echo "The Reversed String: $output"

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 [ true ]
do
clear
tput cup 7 25
echo "WELCOME TO DURGASOFT"
sleep 2
clear
tput cup 7 25
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
177  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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.

Q5) Write a Script to Read Employee Data and Insert into


emp.txt File?
#! /bin/bash

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])
break
;;
esac
done
echo "Open emp.txt to see all employees information"

Output:
durgasoft@durgasoft:~/scripts$ test.sh
Employee Number: 100
Employee Name: Sunny
Employee Salary: 1000
Employee Address: Hyderabad
Employee Record Inserted Successfully
Do you want to insert one more record [Yes|No]: y
Employee Number: 200
Employee Name: Bunny
Employee Salary: 2000
Employee Address: Mumbai
Employee Record Inserted Successfully
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
178  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

Q6) Write a Script to implement cat Command with -n Option?


durgasoft@durgasoft:~/scripts$ cat -n emp.txt
1 100:Sunny:1000:Hyderabad
2 200:Bunny:2000:Mumbai
3 300:Chinny:3000:Hyderabad
4 400:Vinny:4000:Chennai

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

Syntax -2: To read data from the file by using while loop
while read line
do
do something with that line
done < emp.txt

test.sh
#! /bin/bash

fname=$1
if [ ! -f $fname ]; then
echo "Please provide already existing regular file only"
exit 1
fi

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
179  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
4 400: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.

Q7) Write a Script to Print 1 to 5 by using until Loop?


#! /bin/bash
i=1
until [ $i -gt 5 ]
do
echo $i
let i++
done

durgasoft@durgasoft:~/scripts$ test.sh
1
2
3
4
5

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
180  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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

Eg 1: To print numbers from 1 to 5.


#! /bin/bash

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

for course in java unix python testing datascience


do
echo "Course Name: $course"
done

Output:
durgasoft@durgasoft:~/scripts$ test.sh
Course Name: java
Course Name: unix
Course Name: python
Course Name: testing
Course Name: datascience

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
181  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

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
echo "The number of values: $count"

Output:
durgasoft@durgasoft:~/scripts$ test.sh
10
20
30
40
50
60
70
80
90
100
The number of values: 10

Q9) Write a Script to Display all File Names Present in Current


Working Directory?
#! /bin/bash

for name in *
do
if [ -f $name ]; then
echo $name
fi
done

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
182  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q10) Write a Script to append Current Date and Time, Current


Month Calander in every .txt File Present in Current Working
Directory?
#! /bin/bash

for fname in *.txt


do
date >> $fname
cal >> $fname
done
echo "Task Completed"

Q11) Write a Script that Print all Command Line Arguments?


#! /bin/bash

if [ $# -ne 0 ]; then

count=1
for arg in $@
do
echo "Command Line Argument - $count: $arg"
let count++
done
else
echo "Command line arguments are not passed"
fi

Output:
durgasoft@durgasoft:~/scripts$ test.sh
Command line arguments are not passed
durgasoft@durgasoft:~/scripts$ test.sh 10 20 30 40
Command Line Argument - 1: 10
Command Line Argument - 2: 20
Command Line Argument - 3: 30
Command Line Argument - 4: 40
durgasoft@durgasoft:~/scripts$ test.sh learning linux is very easy
Command Line Argument - 1: learning
Command Line Argument - 2: linux
Command Line Argument - 3: is
Command Line Argument - 4: very
Command Line Argument - 5: easy

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
183  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

1) Write a Script to Display all Employees Information where Salary


is Greater than 2500
#! /bin/bash
for record in $(cat emp.txt)
do
sal=$(echo $record | cut -d ":" -f 3)
if [ $sal -gt 2500 ]; then
echo $record
fi
done

2) Write a Script to Save all Employees Information where Salary is


Greater than 2500 and City is Hyderabad to hyd.txt
#! /bin/bash

for record in $(cat emp.txt)


do
sal=$(echo $record | cut -d ":" -f 3)
city=$(echo $record | cut -d ":" -f 4)
if [ $sal -gt 2500 -a $city = "Hyderabad" ]; then
echo $record >> hyd.txt
fi
done
echo "Task Completed"

3) Write a Script to Display Minimum and Maximum Salaries?


#! /bin/bash
max=$(cat emp.txt | head -1 | cut -d ":" -f 3)
min=$(cat emp.txt | head -1 | cut -d ":" -f 3)
max_record=$(cat emp.txt | head -1)
min_record=$(cat emp.txt | head -1)
for record in $(cat emp.txt)
do
sal=$(echo $record | cut -d ":" -f 3)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
184  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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
echo "The Maximum Salary:$max"
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)"

Q12) Write a Script to Display Multiple Files Content to the


Terminal and all File Names passed as Command Line Arguments?
#! /bin/bash

if [ $# -ne 0 ]; then
for fname in $@
do
if [ -f $fname ]; then
echo "$fname content:"
echo "====================="
cat $fname
else
echo "$fname does not exist or it is not a regular file"
fi
done
else
echo "Please pass atleast one file name"
fi

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
185  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q13) Write a Script to append Multiple Files Content to a Single File


result.txt. File Names are passed as Command Line Arguments?
#! /bin/bash

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

Alternative Syntax of for Loop (Advanced for Loop):


Old Style of for Loop:
for variable in item1 item2 ... itemN
do
body
done

Advanced for Loop:


for ((i=1; i<10; i++))
do
body
done

Q14) Write a Script to Print Numbers from 0 to 4 by using


advanced for Loop?
#! /bin/bash
for ((i=0;i<5;i++))
do
echo $i
done

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
186  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Output:
0
1
2
3
4

Q15) Write a Script to Print Numbers for Count Down from


provided Number to 1 by using advanced for Loop?
#! /bin/bash
read -p "Enter n value:" n
for((i=n,i>=1;i--)
do
echo $i
sleep 1.5
done

Q16) Write a Script to Display 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
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
187  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q17) Write a Script to generate Hotel Bill based on Customer


selected Items. The Items and Price Information is as follows
A  Vadapov (Each Plate Rs 30 /-)
B  Dosa (Each Plate Rs 50 /-)
C  Poori (Each Plate Rs 40 /-)
D  Idli (Each Plate Rs 25 /-)

#! /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)
read -p "Enter the number of plates of Idli, you required:" quantity
amount=$[amount+quantity*25]
;;
*)
echo "You entered invalid option. Choose Again"
continue
esac
read -p "Do you want to order any other item[Yes|No]:" option
case $option in
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
188  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

[Yy]|[Yy][Ee][Ss])
continue
;;
[Nn]|[Nn][Oo])
break
;;
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 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:B
Enter the number of plates of Dosa, you required:2
Do you want to order any other item[Yes|No]:Yes

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
189  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

Your Total Bill Amount: Rs 350/-


Thanks for visiting DURGA HOTEL

Q18) Write a Script to Test whether the given Number is Prime


Number OR not?
If any number has two factors (1 and itself), such type of number is said to be prime number.

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
echo "$n is a PRIME number"

durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is prime or not:23
23 is PRIME number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is prime or not:29
29 is PRIME number
durga@durga-VirtualBox:~/scripts$ test.sh
Enter Any Number to test whether it is prime or not:35
35 is not PRIME number

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
190  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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.

How to Create Arrays:


1. If we know elements at the beginning:
courses=(Java Python Linux Django)

2. If we don't know elements at the biginning:


courses[0]=Java
courses[1]=Python
courses[2]=Linux
courses[3]=Django

The index values need not be consecutive.We can take randomly.

courses[10]=DataScience
courses[20]=Devops

How to Access Elements:


We can access array elements by using index which is zero based.i.e the index of first
element is zero.

${courses[0]}  First element


${courses[1]}  Second element
${courses[@]} All elements present inside array.
${courses[*]}  All elements present inside array into a single string separated by first
character in IFS(Internal Field Separator)
${!courses[@]} It returns all indexes where elements are available.
${#courses[@]} It returns the number of elements present inside array.
${#courses[0]}  It returns the length of first element.

Demo Script:
#! /bin/bash
courses[0]=Java
courses[1]=Python
courses[2]=Linux
courses[3]=Django
courses[10]=DataScience
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
191  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

courses[20]=Devops
echo "First Element : ${courses[0]}"
echo "Second Element : ${courses[1]}"
echo "All Elements with @ : ${courses[@]}"
echo "All elements with * : ${courses[*]}"
echo "The indices where elements are available : ${!courses[@]}"
echo "The total number of elements : ${#courses[@]}"
echo "The length of first element : ${#courses[0]}"

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

echo "All elements by using while loop:"


while [ $i -lt $size ]
do
echo ${fruits[$i]}
let i++
done

echo "All elements by using for loop:"


for fruit in ${fruits[@]}
do
echo $fruit
done

echo "All elements by using advanced for loop:"


for (( i=0; i < ${#fruits[@]}; i++ ))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
192  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

do
echo ${fruits[$i]}
done

Output:
durga@durga-VirtualBox:~/scripts$ test.sh
All elements by using while loop:
Apple
Orange
Banana
Mango
All elements by using for loop:
Apple
Orange
Banana
Mango
All elements by using advanced 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

2) After creating array we can add extra elements also


fruits=("Apple" "Orange" "Banana" "Mango")
fruits[4]="Sapota"

Q2) Write a Script for accessing Array Elements by using for Loop if
Indices are Random?
#! /bin/bash
declare -a fruits
fruits[10]="Apple"
fruits[20]="Banana"
fruits[30]="Orange"
fruits[40]="Mango"

echo "Accessing based on Values:"


for fruit in ${fruits[@]}
do
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
193  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
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

Accessing based on Index:


Apple
Banana
Orange
Mango

Q3) Is it Possible to Remove Array Elements?


Yes possible by using unset command.

Eg:
#! /bin/bash
declare -a fruits
fruits[10]="Apple"
fruits[20]="Banana"
fruits[30]="Orange"
fruits[40]="Mango"

echo "All Array Elements Before Removal: ${fruits[@]}"


unset fruits[20]
unset fruits[40]
echo "All Array Elements After Removal: ${fruits[@]}"

Output:
durga@durga-VirtualBox:~/scripts$ test.sh
All Array Elements Before Removal: Apple Banana Orange Mango
All Array Elements After Removal: Apple Orange

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
194  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
UNIX/LINUX

Q4) Write a Script to Store given n Numbers in to an Array?


#! /bin/bash
read -p "Enter The Number Of values:" n

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"

nd
DURGASOFT, # 202, 2 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

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
196  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
abcd.txt: READ(Y) WRITE(Y) EXECUTE(N)
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)

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
197  88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]

You might also like