Professional Documents
Culture Documents
Unix Notes BCA II-1
Unix Notes BCA II-1
These programs are often quite complicated and must be able to properly manage the
necessary tasks required by the different users connected to it.
The users will typically be at terminals or computers that give them access to the system
through a network, as well as other machines on the system such as printers.
Examples:
Ubuntu
macOS
All linux based OS
Unix
IBM AS400
Windows 10
When Multics was withdrawn Ken Thompson and Dennis Ritchie needed to rewrite
an operating system to play space travel on another smaller machine. The result was
a system that a punning colleague called UNICS (Uniplexed Information and
Computing Service)--an 'emasculated Multics'.
Brian Kernighan claims the coining for himself, and adds that "no one can
remember" who came up with the final spelling Unix.
The Unix operating system was first presented formally to the outside world at the
1973 Symposium on Operating Systems Principles, where Ritchie and Thompson
delivered a paper.
Unix Features
o Multiuser capability: Multiple users can access the same system resources like
memory, hard disk, etc. But they have to use different terminals to operate.
o Multitasking: More then one function can be performed simultaneously by dividing
the CPU time intelligently.
o Portability: Portability doesn't mean it is smaller in file size or can be carried in pen
drives or memory cards. It means that it support different types of hardware.
o Security: It provides security in three ways namely authenticating (by assigning
password and login ID), authorization (by assigning permission to read, write and
execute) and encryption (converts file into an unreadable format).
o File System: Provides hierarchical file system in which files and directories are
arranged.
o UNIX shell: UNIX has a simple user interface called the shell that has the power to
provide the services that the user wants. It protects the user from having to know the
intricate hardware details.
o Pipes and Filters: UNIX has facilities called Pipes and Filters which permit the user
to create complex programs from simple programs.
o Utilities: UNIX has over 200 utility programs for various functions. New utilities can
be built effortlessly by combining existing utilities.
o Software Development Tools: UNIX offers an excellent variety of tools for software
development for all phases, from program editing to maintenance of software.
Versions of UNIX
There are many different versions of UNIX. Until a few years ago, there were two main
versions: the line of UNIX releases that started at AT&T (the latest is System V Release 4),
and another line from the University of California at Berkeley (the latest version is BSD 4.4).
Some other major commercial versions include SunOS, Solaris, SCO UNIX, AIX, HP/UX,
and ULTRIX.
Many versions of UNIX, including System V Release 4, merge earlier AT&T releases with
BSD features. The recent POSIX standard for UNIX-like operating systems defines a single
interface to UNIX.
System Structure
Here is a basic block diagram of a Linux system –
The main concept that unites all the versions of UNIX is the following four basics −
Kernel − The kernel is the heart of the operating system. It interacts with the hardware and
most of the tasks like memory management, task scheduling and file management.
Shell − The shell is the utility that processes your requests. When you type in a command at
your terminal, the shell interprets the command and calls the program that you want. The
shell uses standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are the
most famous shells which are available with most of the Unix variants.
Application - The final layer of the UNIX OS is the Utilities and Applications layer. This
layer includes the word processors, graphic programs and database management programs.
Kernel and its function: Kernel is also called as the heart of the operating system and the
every operation is performed by using the kernel, when the kernel receives the request
from the shell then this will process the request and display the results on the screen.
The various types of operations those are performed by the kernel are as followings:-
1) It controls the state of the process means it checks whether the process is
running or process is waiting for the request of the user.
2) Provides the memory for the processes those are running on the system means kernel runs
the allocation and de-allocation process , first when we request for the service then the kernel
will provides the memory to the process and after that he also release the memory which is
given to a process.
3) The kernel also maintains a time table for all the processes those are running means the
kernel also prepare the schedule time means this will provide the time to various process
of thecpu and the kernel also puts the waiting and suspended jobs into the different memory
area.
4) When a kernel determines that the logical memory doesn’t fit to store the programs. then
he uses the concept of the physical memory which will stores the programs into
temporary manner. Means the physical memory of the system can be used as temporary
memory.
5) Kernel also maintains all the files those are stored into the computer system and the
kernel also stores all the files into the system as no one can read or write the files
without any permissions. So that the kernel system also provides us the facility to use the
passwords and also all the files are stored into the particular manner.
System Call: In computing, a system call is the programmatic way in which a computer program
requests a service from the kernel of the operating system it is executed on.
A system call is a way for programs to interact with the operating system. A computer program makes
a system call when it makes a request to the operating system’s kernel.
System call provides the services of the operating system to the user programs via Application
Program Interface(API). It provides an interface between a process and operating system to allow
user-level processes to request services of the operating system.
System calls are the only entry points into the kernel system. All programs needing resources must
use system calls.
C shell (csh)
TENEX/TOPS C shell (tcsh)
Bourne Shell
The original Bourne shell is named after its developer at Bell Labs, Steve Bourne. It was the first shell
used for the Unix operating system. It is known as “sh”
C Shell
The C shell, as its name might imply, was designed to allow users to write shell script programs using
a syntax very similar to that of the C programming language. It is known as "csh."
TC Shell
TC shell is an expansion upon the C shell. It has all the same features, but adds the ability to use
keystrokes from the Emacs word processor program to edit text on the command line.It is also known
as "tcsh."
Korn Shell
Korn Shell was also written by a developer at Bell Labs, David Korn. It attempts to merge the features
of the C shell, TC shell and Bourne shell under one package. It is known as "ksh."
Bourne-Again Shell
The Bourne-Again shell is an updated version of the original Bourne shell that was created by the
Free Software Foundation for its open source GNU project. For this reason, it is a widely used shell in
the open source community. It is known as "bash."
File System
Unix file system is a logical method of organizing and storing large amounts of information in a
way that makes it easy to manage.
A file is a smallest unit in which the information is stored. Unix file system has several important
features.
All data in Unix is organized into files. All files are organized into directories. These directories are
organized into a tree-like structure called the file system.
Files in Unix System are organized into multi-level hierarchy structure known as a directory tree. At
the very top of the file system is a directory called “root” which is represented by a “/”. All other files
are “descendants” of root.
Inode Table: Inode is a data structure that keeps track of all the information about a file.
Whenever a user or a program needs to access a file, the operating system first searches for the exact
and unique inode (inode number), in a table called as an inode table.
In fact the program or the user who needs access to a file, reaches the file with the help of the inode
number found from the inode table.
The kernel contains two other data structures, the file table and the user file descriptor table.
The file table is a global kernel structure, but the user file descriptor table is allocated per process.
When a process opens or creates a file, the kernel allocates an entry from each table, corresponding to
the file's inode.
Entries in the three structures - user file descriptor table, file table, and inode table - maintain the state
of the file and the user's access to it.
The file table keeps track of the byte offset in the file where the user's next read or write will start, and
the access rights allowed to the opening process. The user file descriptor table identifies all open files
for a process
The kernel returns a file descriptor for the open and creat system calls, which is an index into the user
file descriptor table.
When executing read and write system calls, the kernel uses the file descriptor to access the user file
descriptor table, follows pointers to the file table and inode table entries, and, from the inode, finds the
data in the file.
Link:
In Linux, “everything is a file” and a file is fundamentally a link to an inode (a data structure
that stores everything about a file apart from its name and actual content). Creating links is a
kind of shortcuts to access a file
There are two main types of links that can be created: "hard" links, and "soft" or symbolic
links.
Soft Link:A symbolic link is a special file that points to another file or directory, which is
called the target.
Each soft linked file contains a separate Inode value that points to the original file.
Multiple symbolic links can even be created to the same target file, allowing the target to be
accessed by multiple names.
The symbolic link does not contain a copy of the target file's data, it contains path of original
file.
ln -s filename linkname
Example:
$ ln –s xyz abc
$ ls –l
_rwxrwxrwx 1 user 7 Apr 17 17:40 xyz
lrwxrwxrwx 1 user 7 Apr 17 17:40 abc -> xyz
The "l" at the beginning of the line, indicating that the file is a symbolic link.Also, notice that
after abc is the "->" symbol, followed by the name of the target.
Hard Link: Each hard linked file is assigned the same Inode value as the original, therefore
they reference the same physical file location. Hard links more flexible and remain linked
even if the original or linked files are moved throughout the file system.
ls -l command shows all the links with the link column shows number of links.
Removing any link, just reduces the link count, but doesn’t affect other links.
If original file is removed then the link will still show the content of the file.
Looking at the output above, using ls command, the new file is not indicated as a link, it is
shown as a regular file.
Who Command
It will display the list of users who are logged in to the computer.
$ who
amrood ttyp0 Oct 8 14:10
bablu ttyp2 Oct 4 09:08
qadir ttyp4 Oct 8 12:09
whoami
It tells you about the system's username.
$ whoami
amrood
pwd Command
pwd (print working directory) command displays current location we are working on. It will
give the whole path starting from the root ending to the directory.
Example:
$ pwd
/home/disha
cd Command
The cd command, which stands for “Change Directory”, changes the shell’s current working
directory.
Syntax:
cd [Options][Directory]
Example:
$ cd /usr/local/sample
$ pwd
/usr/local/sample
mkdir Command
The mkdir stands for 'make directory'. With the help of mkdir command, you can create a
new directory
Syntax:
mkdir <dirname>
Example
$ mkdir disha
rm Command
The 'rm' means remove. This command is used to remove a file.
Syntax:
rm[option] <file name>
rm Options:
Option Description
rm *extension Used to delete files having same extension.
rm -r or R To delete a directory recursively.
rm -i Remove a file interactively.
rm -rf Remove a directory forcefully.
ls Command
The ls is the list command. It will show the full list or content of the directory.
$ ls
ls option Description
ls -a In Linux, hidden files start with . (dot) symbol and they are not visible in the regular
directory. The (ls -a) command will enlist the whole list of the current directory
including the hidden files.
ls -l It will show the list in a long list format.
ls -lh This command will show you the file sizes in human readable format. Size of the
file is very difficult to read when displayed in terms of byte. The (ls -lh)command
will give you the data in terms of Mb, Gb, Tb, etc.
ls --color This command is used to print list as colored or discolored.
=[VALUE
]
ls -li This command prints the index number if file in the first column.
ls -p It is used to identify the directory easily by marking the directories with a slash (/)
line sign.
mv Command
mv command is used to move existing file or directory from one location to another. It is also
used to rename a file or directory. While renaming a file the inode number of file will remain
the same.
Example:
$ mv doc document
Option Function
mv -i Asks for permission to over write.
mv * Move multiple files to a specific directory.
lp Command
lp is used to print files.
Syntax:
lp options file(s)
-U username Specifies the username to use when connecting to the server.
-d destination Prints files to the destination printer.
-o media=size Sets the page size to size. Most printers support at least the size names
chmod Command:
chmod is used to change the permissions of files or directories.
Syntax:
There are two ways to represent these permissions: with symbols (alphanumeric characters), or
with octal numbers (the digits 0 through 7).
Example:
This example uses symbolic permissions notation. The letters u, g, and o stand for "user", "group",
and "other". The equals sign ("=") means "set the permissions exactly like this," and the letters "r",
"w", and "x" stand for "read", "write", and "execute", respectively.
Here the digits 7, 5, and 4 each individually represent the permissions for the user, group, and others,
in that order. Each digit is a combination of the numbers 4, 2, 1, and 0:
4 stands for "read",
2 stands for "write",
1 stands for "execute", and
0 stands for "no permission."
It searches for the given regular expression patterns, using a fairly efficient matching algorithm, in the
given files and outputs to stdout.
Ex.
Ignoring Case (-i) This option ignores case for pattern matching
$ grep –i ‘agarwal’ emp
3564|sudhir Agarwal|executive|personnel|7800
Deleting Lines(-v)This option selects all lines except those containing the pattern
$ grep –v ‘director’ emp>otherlist
Displaying Line Number(-n)This option displays the line number along with the lines
$ grep –n ‘marketing’ emp
3 : 5678|J. B. Saxena |g.m. |marketing|6000
15 : 5678|V.K. Agrawal |director|marketing|8000
Counting Lines (-c) This option counts the total lines containing the pattern
$ grep–c “sales” emp
Regular Expression Regular Expressions are special characters which help search data
and matching complex patterns. Regular expressions are shortened as 'regexp' or 'regex'. They are
used in many Linux programs like grep, bash, rename, sed, etc.
BRE
ERE
sed Command SED command in UNIX is stands for stream editor and it can perform lot’s of
function on file like, searching, find and replace, insertion or deletion. Though most common use of
SED command in UNIX is for substitution or for find and replace. By using SED you can edit files
even without opening it, which is much quicker way to find and replace something in file.
Syntax:
1. Line Addressing
2. Context Addressing
Note: For Line addressing and Context addressing example refer Sumitabh Das Book (Page No. 256-261)
Replacing or substituting string : Sed command is mostly used to replace the text in a file. The
below simple sed command replaces the word “unix” with “linux” in the file.
By default, the sed command replaces the first occurrence of the pattern in each line and it won’t
replace the second, third…occurrence in the line.
Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first,
second occurrence of a pattern in a line. The below command replaces the second occurrence of the
word “unix” with “linux” in a line.
Replacing all the occurrence of pattern in a line: The substitute flag /g (global replacement)
specifies the sed command to replace all the occurrences of the string in the line.
Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc
and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed
command replaces the third, fourth, fifth… “unix” word with “linux” word in a line.
Replacing string on a specific line number : You can restrict the sed command to replace the string
on a specific line number. An example is
Deleting lines from a particular file : SED command can also be used for deleting lines from a
particular file. SED command is used for performing deletion operation without even opening the file
Examples:
1. To Delete a particular line say n in this example
Syntax:
Example:
Syntax:
Syntax:
Example:
pr [OPTION]... [FILE]...
awk command
Short for "Aho, Weinberger, and Kernighan," .It searches files for text containing a pattern.
When a line or text matches, awk performs a specific action on that line/text.
awk syntax
-v var=value Assigns the value value to the variable var before executing the awk program.
Consider the following text file as the input file for all cases below.
$cat > employee.txt
1. Default behavior of Awk : By default Awk prints every line of data from the specified file.
$ awk '{print}' employee.txt
Output:
ajay manager account 45000
Output:
ajay manager account 45000
3. Splitting a Line into Fields: For each record i.e line, the awk command splits the record
delimited by whitespace character by default and stores it in the $n variables. If the line has
4 words, it will be stored in $1, $2, $3 and $4 respectively. Also, $0 represents the whole
line.
$ awk '{print $1,$4}' employee.txt
Output:
ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000
Built In Variables In Awk: Awk’s built-in variables include the field variables—$1, $2, $3, and
so on ($0 is the entire line) — that break a line of text into individual words or pieces called
fields.
NR (Line number): NR command keeps a current count of the number of input records.
Remember that records are usually lines. Awk command performs the pattern/action
statements once for each record in a file.
NF (Last Field): NF command keeps a count of the number of fields within the current input
record.
FS: FS command contains the field separator character which is used to divide fields on the
input line. The default is “white space”, meaning space and tab characters. FS can be
reassigned to another character (typically in BEGIN) to change the field separator.
RS: RS command stores the current record separator character. Since, by default, an input
line is the input record, the default record separator character is a newline.
OFS: OFS command stores the output field separator, which separates the fields when Awk
prints them. The default is a blank space. Whenever print has several parameters separated
with commas, it will print the value of OFS in between each parameter.
ORS: ORS command stores the output record separator, which separates the output lines
when Awk prints them. The default is a newline character. print automatically outputs the
contents of ORS at the end of whatever it is given to print.
Examples:
Use of NR built-in variables (Display Line Number)
$ awk '{print NR,$0}' employee.txt
Output:
1 ajay manager account 45000
Output:
ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000
Another use of NR built-in variables (Display Line From 3 to 6)
$ awk 'NR==3, NR==6 {print NR,$0}' employee.txt
Output:
3 varun manager sales 50000
For example:
$ cat file1
Name,Domain,Expertise
Deepak,Banking,MQ Series
Neha,Telecom,Power Builder
Vijay,Finance,CRM Expert
Guru,Migration,Unix
Name
Deepak
Neha
Vijay
Guru
Name Expertise
Deepak MQ Series
Guru Unix
For example:
$cat student.txt
Jones
2143
78
84
77
Gondrol
2321
56
58
45
RinRao
2122
38
37
65
Jones 2143
Gondrol 2321
RinRao 2122
Mounting is the operation you perform to cause the file system on a physical storage device
(a hard drive partition or a CD-ROM) to appear as part of the Linux file system.
You can use the mount command to manually mount a device on the Linux file system at a
specified directory. That directory is the mount point. For example, to mount the DVD/CD-
ROM drive at the /media/cdrom directory, type the following command (after logging in as
root):
The mount command reports an error if the DVD/CD-ROM device is mounted already or if
no CD or DVD media is in the drive. Otherwise, the mount operation succeeds, and you can
access the contents of the DVD or CD through the /media/cdrom directory.
To unmount a device when you no longer need it, use the umount command. For example,
for a DVD/CD-ROM device with the device name /dev/cdrom, type the following command
to unmount the device:
#umount /dev/cdrom
The /etc/fstab file is a configuration file — a text file containing information that the mount
and umount commands use. Each line in the /etc/ fstab file provides information about a
device and its mount point in the Linux file system.
fdisk: Creating Partition
We will partition the disks to create FS on them. In Linux on SCSI drives you can create 3 Primary
Partitions and 1 Extended Partition. The extended partition is further used to create Logical
partitions which can be treated as Primary partition by dependable to extended partition. The
maximum supportable no. of partitions in SCSI drivers are 15 and IDE are 63.
#fdisk /dev/hda
In order to access a filesystem in Linux we first need to mount it. Mounting a filesystem simply
means making the particular filesystem accessible at a certain point in the Linux directory tree.
The filesystem that we have created can be unmounted by the file system name or mount point.
#umount /oracle or
# umount /dev/hda3
fsck: File System Checking
The fsck command is used to check and repair a damaged file system. It’s generally run when a file
system fails to mount.
# fsck /dev/sda6
System Call: A System call is a routine built into the kernel and performs a very basic function that
requires communication with the CPU, memory and devices. We can invoke them as functions from a C
program running on Linux.
When we execute a C program, the CPU runs in user mode until a system call is invoked. In this mode, the
process has access to a limited section of the computer’s memory, and can execute a restricted set of machine
instructions. However, when the process invokes a system call the CPU switches from user mode to a more
privileged mode-the Kernel mode. After the system call has returned, the CPU switches back to user mode.
Buffer Cache: The read and write calls never access the disk directly. Rather they read and write to a pool
of buffers maintained by the kernel for this purpose, called the buffer cache. If the kernel buffer is found to be
empty during a read, the kernel instructs the disk controller to read data from disk and fill up the cache.
o Command Mode: In command mode, actions are taken on the file. The vi editor starts in
command mode. Typed words will act as commands in vi editor. To pass a command you
have to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. Esc key will take
you to the command mode from insert mode.
o Ex Mode: This mode is used to handle files(like saving). Pressing a: in the command
mode invokes this mode.
Command macros: Using Macro feature we can record and play a sequence of actions
inside the editor.
Steps to Record and Play inside Vi
1. Start recording by pressing q, followed by a lower case character to name the macro
2. Perform any typical editing, actions inside Vim editor, which will be recorded
3. Stop recording by pressing q
4. Play the recorded macro by pressing @ followed by the macro name
5. To repeat macros multiple times, press : NN @ macro name. NN is a number
$ vim sequence-test.txt
1.
4. Copy the 1st line to 2nd line to have two lines with 1 . as shown
below
Type: Esc yy followed by p
1.
1.
By placing the cursor at the 2nd line, press Ctrl+a which increment the number to 2. as
shown below.
$ vim sequence-test.txt
1.
2.
Press q to stop the recording. You’ll notice that recording message at the bottom of the vi is
now gone.
Shell is an environment in which we can run our commands, programs, and shell
scripts. There are different flavors of a shell, just as there are different flavors of
operating systems.
The prompt, $, which is called the command prompt, is issued by the shell. While
the prompt is displayed, we can type a command. Shell reads the input after
pressing the Enter key.
Example
Here is a simple example that uses the while loop to display the
numbers zero to nine −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
0
1
2
3
4
5
6
7
8
9
Syntax
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Example
Here is a simple example that uses the for loop to span through the
given list of numbers −
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
0
1
2
3
4
5
6
7
8
9
The while loop is perfect for a situation where you need to execute a set
of commands while some condition is true. Sometimes you need to
execute a set of commands until a condition is true.
Syntax
until command
do
Statement(s) to be executed until command is true
done
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a = `expr $a + 1`
done
0
1
2
3
4
5
6
7
8
9