0% found this document useful (0 votes)
92 views132 pages

Unix Programming (Code:18CS56) : Presented by

Unix Programming is a course taught at Alva's Institute of Engineering and Technology, Moodbidri. The syllabus covers Unix components/architecture, files, file attributes and permissions, the shell's interpretive cycle, connecting commands, and shell programming. Module 1 focuses on introductions, Unix files, and basic Unix commands over 8 hours. Key topics include the history and architecture of Unix, features like multi-user access and multi-tasking, and commands like ls, cat, and pwd.

Uploaded by

Adam Sanadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
92 views132 pages

Unix Programming (Code:18CS56) : Presented by

Unix Programming is a course taught at Alva's Institute of Engineering and Technology, Moodbidri. The syllabus covers Unix components/architecture, files, file attributes and permissions, the shell's interpretive cycle, connecting commands, and shell programming. Module 1 focuses on introductions, Unix files, and basic Unix commands over 8 hours. Key topics include the history and architecture of Unix, features like multi-user access and multi-tasking, and commands like ls, cat, and pwd.

Uploaded by

Adam Sanadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 132

Unix Programming(Code:18CS56)

Presented by:
VENKATESH
Senior Associate Professor
Department of Computer Science and Engineering
Alva’s Institute of Engineering and Technology, Moodbidri
Module-1 SYLLABUS

•Introduction:
•Unix files:
MODULE-1 INTRODUCTION SYLLABUS
• Unix Components/Architecture. Features of Unix. The UNIX
Environment and UNIX Structure, Posix and Single Unix
specification. General features of Unix commands/
command structure. Command arguments and options.
Basic Unix commands such as echo, printf, ls, who,
date,passwd, cal, Combining commands. Meaning of
Internal and external commands. The type command:
knowing the type of a command and locating it. The root
login. Becoming the super user: su command.
MODULE-1 -- UNIX FILES SYLLABUS
• Naming files. Basic file types/categories. Organization of
files. Hidden files. Standard directories. Parent child
relationship. The home directory and the HOME variable.
Reaching required files- the PATH variable, manipulating the
PATH, Relative and absolute pathnames. Directory
commands – pwd, cd, mkdir, rmdir commands. The dot (.)
and double dots (..) notations to represent present and
parent directories and their usage in relative path names.
File related commands – cat, mv, rm, cp, wc and od
Module-2 SYLLABUS
• File attributes and permissions:
• The shells interpretive cycle:
• Connecting commands:
• Shell programming:
File attributes and permissions:
• The ls command with options. Changing file permissions:
the relative and absolute permissions changing methods.
Recursively changing file permissions. Directory
permissions.
The shells interpretive cycle:
Connecting commands:
Shell programming:
Textbooks:
• 1) Sumitabha Das., Unix Concepts and Applications., 4thEdition.,
Tata McGraw Hill ( Chapter 1,2,3,4,5,6,8,13,14)
• 2) W. Richard Stevens: Advanced Programming in the UNIX
Environment,2nd Edition, Pearson Education, 2005
(Chapter3,7,8,10,13,15)
• 3) Unix System Programming Using C++ - Terrence Chan, PHI,
1999. ( Chapter 7,8,9,10)
Reference Books:
• 1. M.G. Venkatesh Murthy: UNIX & Shell Programming,
Pearson Education.
• 2. Richard Blum , Christine Bresnahan : Linux Command Line
and Shell Scripting Bible, 2nd Edition, Wiley,2014.
Module-1 (8hrs.) Syllabus
• Introduction:
• Unix files:
Module-1 (8hrs.) Syllabus -- Introduction
• Unix Components/Architecture. Features of Unix. The UNIX
Environment and UNIX Structure, Posix and Single Unix
specification. General features of Unix commands / command
structure. Command arguments and options.
• Basic Unix commands such as echo, printf, ls, who, date, passwd,
cal, Combining commands. Meaning of Internal and external
commands.
• The type command: knowing the type of a command and
locating it. The root login.
• Becoming the super user: su command.
Module-1 (8hrs.) Syllabus -- Unix files
• Naming files. Basic file types/categories. Organization of files.
Hidden files. Standard directories. Parent child relationship. The
home directory and the HOME variable. Reaching required files-
the PATH variable, manipulating the PATH, Relative and absolute
pathnames. Directory commands – pwd, cd, mkdir, rmdir
commands. The dot (.) and double dots (..) notations to represent
present and parent directories and their usage in relative path
names. File related commands – cat, mv, rm, cp, wc and od
commands.
Module-1 (8hrs.)
• What is Unix?
• A history of Unix.
• Architecture(Components) of Unix.
• Features of Unix.
What is Unix?
• OS is a set of programs that act as a link between the user
and the computer.
• Unix is command user interface O.S
• It can be able to work on any type of computers.
• Unix O.S is a multiuser and multitasking O.S.
• Multiuser: Several people can use a Unix computer at the
same time.
• Multitasking: A user can also run multiple programs at the
same time.
A history of Unix
• In 1969, at AT&T popularly known as Bell Labs started
as a project, a team lead by Ken Thompson and
Dennis Ritchie.
• This project name is MULTICS
• It is the first official O.S in the s/w industries.
• It is modern O.S’s origin.
• Based on this o.s now we are enjoying all modern
O.S’s.
Contd…
• Drawback: MULTICS maximum support 2 users and
no networking support.
• In 1971 to recover this drawback a new project called
UNICS(developed on low level language or Assembly
level language or symbolic language).
• In 1972, Dennis Ritchie launched C language in the IT
industry.
Contd…
• In 1973, a group of members lead by Ken Thompson, Dennis
Ritchie along with other members they re-implemented
UNICS on C language and renamed as UNIX.
• There are various Unix variants available in the Market =>
Solaris Unix, AIX, HP Unix and BSD are a few examples.
• Linux is also a flavor of Unix which is freely available.
The Unix Architecture

• The UNIX architecture has three important


agencies:
1) Division of labor: Kernel and shell.
2) The file and process.
3) The system calls.
Contd…
• How does the unix shell and the kernel work together.
• Ex: mv myfile myfilenew (which has the effect of renaming
the file myfile).
• The unix shell searches the file store for the file containing
the program mv, and then requests the kernel, through
system calls, to execute the program mv on myfile. When
the process mv myfile has finished running, the unix shell
then returns the UNIX prompt to the user, indicating that it
is waiting for further commands.
Contd…
contd…
• Division of labor: Kernel and shell
• The kernel interacts with the machine's hardware.
• The shell interacts with the user.
• The Kernel: The core of the operating system - a collection of
routines mostly written in C.
• It is loaded into memory when the system is booted and
communicates directly with the hardware.
• User programs (the applications) that need to access the hardware
use the services of the kernel, which performs the job on the user's
behalf.
Contd…
• These programs access the kernel through a set of functions called
system calls.
• Apart from providing support to user's program, kernel also does
important housekeeping.
• It manages the system's memory, schedules processes, decides their
priorities and so on.
• The kernel has to do a lot of this work even if no user program is
running.
• The kernel is also called as the operating system - a programs
gateway to the computer's resources.
Contd…
• The Shell: Shell is actually interface between the user and the
kernel.
• Computers don't have any capability of translating commands
into action.
• That requires a command interpreter, also called as the shell.
• Most of the time, there's only one kernel running on the
system, there could be several shells running – one for each
user logged in.
Contd…
• Different types of Shell: Tenex c shell (tcsh)
• Korn shell (ksh)
• Bourne Again Shell (bash)
• Bourne shell (sh)
• C shell (csh)
• Eg. $echo $SHELL
• The shell accepts commands from user, if require rebuilds
a user command, and finally communicates with the
kernel to see that the command is executed.
Contd…
• Example: $ echo Welcome to AIET Moodbidri
Contd…
• Example: $ echo Welcome to AIET Moodbidri
Welcome to AIET Moodbidri
#Shell rebuilds echo command by removing multiple
spaces.
The file and process
• The Unix supports 2 simple entities -->
1) The file and 2) The process.
“Files have places and processes have life”.
The File
• A file is just an array of bytes and can contain
virtually anything.
• Every file in UNIX is part of the one file structure
provided by UNIX.
• UNIX considers directories and devices as
members of the file system.
The Process
• The process is the name given to the file when it
is executed as a program
(Process is program under execution).
• We can say process is an “time image” of an
executable file.
• We also treat process as a living organism which
have parents, children and are born and die.
The System Calls
• The UNIX system calls tell the kernel to carry out various tasks for
the program such as:
Opening a file ---- open()
Writing a file ---- write()
Reading a file ---- read() etc.
• Through these system calls the shell communicate with the kernel.
• The shell contains nearly 100 system calls.
Features of Unix Operating System
• It has 8 features:
1) Multiuser : Multiple users can able to access the system
resources(like RAM, memory and application programs etc.) at
the same time.
2) Multitasking (Multiprogramming): Multiple applications can
able to run at the same time.
Ex: Driving a vehicle while talking to someone.
Cont’d…
• 3) Portability: Means the ability of a piece of software to move
easily from one hardware platform to another.
• 4) The building-block approach: UNIX offers the | (filters) to
combine various simple tools to carry out complex jobs.
Ex: $cat sample #here cat command displays the file contents.
WELCOME TO AIET
$cat sample|wc #here wc counts no. of lines, words and
characters in the file.
1 3 15
Cont’d…
• 5) The UNIX Toolkit:
• Kernel itself doesn't do much useful task for users.
• UNIX offers facility to add and remove many applications as
and when required.
• Tools include general purpose tools, text manipulation tools,
compilers, interpreters, networked applications and system
administration tools.
Cont’d…
• 6) Pattern Matching:
• UNIX features very sophisticated pattern matching features.
• Example: The * (zero or more occurrences of characters) is a
special character used by system to indicate that it can match a
number of filenames.
• Ex: ls sam*
Cont’d…
• 7) Programming Facility:
• The UNIX shell is also a programming language.
• It has all the necessary ingredients, like control structures, loops
and variables, that establish powerful programming language.
• This features are used to design shell scripts – programs that can
also invoke UNIX commands.
• Many of the system's functions can be controlled and automated
by using these shell scripts.
Cont’d…
• 8) Documentation:
• The principal on-line help facility available is the man
command, which remains the most important references for
commands and their configuration files.
• Apart from the man documentation, there's a vast ocean of
UNIX resources available on the Internet.
General features of Unix commands
• a) LOCATING COMMANDS:
• The UNIX is command-based system i.e.,- things happens
because the user enters commands in.
• UNIX commands are rarely more than four characters long.
• All UNIX commands are single words like – cat, ls, pwd, date,
mkdir, rmdir, cd, grep etc.
• The command names are all in lowercase.
Cont’d…
• Example:
• $ DATE
bash : DATE : command not found
• If you want to know the location of executable program (or
command), use type command-
• Example: $ type date
date is /bin/date
• When you execute date command, the shell locates this file in
the /bin directory and makes arrangements to execute it.
Cont’d…
b) The PATH:
• The sequence of directories that the shell searches to look for a
command is specified in its own PATH variable.
Example: $echo $PATH
/bin: /usr/bin: /usr/local/bin: /usr/ccs/bin: /usr/local/java/bin:
Cont’d…
• c) Internal and External commands:
• There is a set of commands which are part of the shell and to
execute them the shell does not need to search the given path
in the PATH variable.
• These are also called shell built-in Commands.

• If the command (file) has an independence existence in the


/bin directory, it is called external command.
Cont’d…
Example: $type echo #echo is an internal command.
echo is shell built-in
$type date #date is an external command
date is /bin/date
• Internal Commands : Commands • External Commands : Commands
which are built into the shell. For all which aren’t built into the shell.
the shell built-in commands, When an external command has to
execution of the same is fast in the be executed, the shell looks for its
sense that the shell doesn’t have to path given in the PATH variable, and
search the given path for them in also a new process has to be
the PATH variable, and also no spawned and the command gets
process needs to be spawned for executed. They are usually located in
executing it. /bin or /usr/bin. For example, when
• Examples: source, cd, fg, etc. you execute the “cat” command,
which usually is at /usr/bin, the
executable /usr/bin/cat gets
executed.
• Examples: ls, cat etc.
What is the difference between internal and external commands?
• Internal commands are commands that are already loaded in the
system. They can be executed any time and are independent.
On the other hand, external commands are loaded when the user
requests for them.
• Internal commands don’t require a separate process to execute
them. External commands will have an individual process.
• Internal commands are a part of the shell while external commands
require a Path.
• If the files for the command are not present in the path, the external
command won’t execute.
Cont’d…
d) Command Structure:
To understand power of UNIX, user must know syntax of UNIX
commands.
The general syntax of UNIX command is –
verb [options][arguments]
Where verb is the command name that can take a set of optional
options and one or more optional arguments.
Commands, options and arguments have to be separated by spaces or
tabs to enable the shell to interpret them as words.
Options
An option is preceded by a minus sign (-) to distinguish it from
filenames.
Ex: ls –l note
-rwxrwxrwx 1 mahesh mahesh 811 Jan 27 12:20 note
There must not be any whitespaces between – and l. Options are also
arguments but given a special name because they are predetermined.
Options can be normally combined with only one –sign. i.e., instead of
using
$ ls –l –a –t
we can as well use,
$ ls –lat
Filename Arguments
• Many UNIX commands use a filename as argument so that the
command can take input from the file. If a command uses a
filename as argument, it will usually be the last argument, after
all options.
• Ex: cp file1 file2
rm file1 file2
• The command with its options and argumens is known as the
command line, which is considered as complete after [Enter]
key is pressed, so that the entire line is fed to the shell as its
input for interpretation and execution.
Basic unix commands
• echo
• printf
• ls
• who
• date
• passwd
• cal
echo: Displaying the message
• echo command is used in shell scripts to display a message
on the terminal or to issue a prompt for taking user input.
Ex: echo "Enter your name:"
Enter your name:
$_
Ex: echo $SHELL
/usr/bin/bash
printf: AN ALTERNATIVE TO ECHO
The printf command is available on most modern UNIX systems, and
is the one we can use instead of echo. The command in the simplest
form can be used in the same way as echo:
$ printf "Enter your name\n"
Enter your name
$_
• printf also uses formatted strings in the same way the C language
function of the same name uses them:
• $ printf "My current shell is %s\n" $SHELL
My current shell is /bin/bash
$_
Cont’d…
• printf also uses formatted strings in the same way the C language
function of the same name uses them:
• $ printf "My current shell is %s\n" $SHELL
My current shell is /bin/bash
$_
The %s format string acts as a placeholder for the value of
$SHELL, and printf replaces %s with the value of $SHELL. %s is
the standard format used for printing strings.
• printf uses many of the formats used by C‟s printf function.
Here are some of the commonly used ones:
• %s – String
• %30s – As above but printed in a space 30 characters wide
• %d – Decimal integer
Cont’d…
• %o – Octal integer
• %x – Hexadecimal integer
• %f – Floating point number
• Ex:
$ printf "The value of 255 is %o in octal and %x in hexadecimal \n" 255 255
The value of 255 is 377 in octal and ff in hexadecimal
Cont’d…
• 3) ls: This command is used to list all files in the current
directory.
• ls with no option list files and directories in bare(plain) format
where we won’t be able to view details like file types, size,
modified date and time, permission and links etc.
• ls options:
• 1) Display One File Per Line Using ls -1
• To show single entry per line, use -1 option as shown below:
Cont’d…
• $ ls -1
bin
boot
cdrom
dev
etc
• 2) Display All Information About Files/Directories Using ls –l:
To show long listing information about the file/directory.
Cont’d…
• $ls –l
total 5
-rw-r- -r- - 1 user metal 512 May 10 10:30 sample1
drwxr-xr-x 2 user metal 875 Feb 12 12:05 helpdir

The above list is preceded by the words 5, which indicates


that a total of 5 blocks are occupied by these files on disk,
each block consisting of 512 bytes in unix (1024bytes in linux).
1) File type
First character specifies the type of the file.
Field Explanation
• – normal file
• d directory
• s socket file
• l link file
Cont’d…
• In field 1 the next 9 character specifies the files
permission.
• Each 3 characters refers to the read, write, execute
permissions for user, group and others.
• In this example, -rw-r- - - - - indicates read-write
permission for user, read permission for group, and no
permission for others.
Cont’d…
• Options Description
• -x Multi-columnar output
• -F Marks executables with *, directories with / and symbolic links with @
• -a Shows all filenames beginning with a dot including . and ..
• -R Recursive list
• -r Sorts filenames in reverse order(ASCII collating sequence by default)
• -d dirname lists only dirname if dirname is a directory.
• -i Displays inode number
Cont’d…
4)Who : WHO ARE THE USERS?
UNIX maintains an account of list of all users logged on to the system.
The who command displays an informative listing of these users:
$ who
Root console Aug 1 01:20 (:0)
Mahesh pts/6 Aug 1 02:16 (pc122.heavens.com)
Kumar pts/8 Aug 1 08:36 (pc125.heavens.com)
The first column shows the usernames(or user-id) of three users
currently working on the system.
Cont’d …
The second column shows the device names of their respective
terminals(These are actually the filenames associated with the
terminals).
The 3rd,4th and 5th columns show the date and time of logging in.
The last column shows the machine name where the user logged in.
Users can log in remotely to a UNIX system, and all users here except
root have logged in remotely from two different machines.
Cont’d…
who with options:
$who –H
NAME LINE TIME COMMENT
Root console Aug 1 01:20 (:0)
Mahesh pts/6 Aug 1 02:16 (pc122.heavens.com)
$_
The above command displays the header information with –H option.
Cont’d…
who with options:
-u option is used with who command displays detailed information of
users:
$ who -Hu
NAME LINE TIME IDLE PID COMMENT
Root console Aug 1 01:20 (0:48) 11040 (:0)
Mahesh pts/6 Aug 1 02:16 . 12346 (pc122.heavens.com)
$
Here a dot against Mahesh shows that activity has occurred in the last
one minute before the command was invoked.
Cont’d…
who with options:
Root user seems to be idling for the last 48 minutes.
The PID is the process-id, a number that uniquely identifies a
process(using ps command we can display the PID).
Basic Unix Commands
5)date: DISPLAYING THE SYSTEM DATE
One can display the current date with the date command, which
shows the date and time to the nearest second.
$date
Tue Sep 15 10:12:30 UTC 2020
Basic Unix Commands
5)date: DISPLAYING THE SYSTEM DATE
The command can also be used with suitable format specifiers as
arguments. Each symbol is preceded by the + symbol, followed
by the % operator, and a single character describing the format.
Basic Unix Commands
5)date: DISPLAYING THE SYSTEM DATE
You can print only the month number using the format +%m.
Example: $date +%m
09
And if need the month name then we can use like this:
$date +%h
Sep
Cont’d…
Or
You can combine them in one command:
$ date + “%h %m”
Sep 09
Cont’d…
There are many other format specifiers, and the useful ones are
listed below:

d – The day of month (1 - 31)


y – The last two digits of the year.
H, M and S – The hour, minute and second, respectively.
D – The date in the format mm/dd/yy
T – The time in the format hh:mm:ss
Basic Unix Commands
6)passwd : CHANGING YOUR PASSWORD
Cont’d…
When you enter a password, the string is encrypted by the system.
This encryption is stored in a file named shadow in the /etc directory.
Ex: /etc/shadow

/
etc
shadow
Basic Unix commands
7) cal : THE CALENDAR
cal command can be used to see the calendar of any specific
month or a complete year.
Syntax:
cal [ [ month] year ]
Everything within the rectangular box is optional. So cal can be
used without any arguments, in which case it displays the
calendar of the current month.
Example
$cal
September 2020
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
Cont’d…
The syntax show that cal can be used with arguments, the
month is optional, but year is not.
To see the calendar of month August 2020, we need to
use two arguments as shown in the next slide page:
Cont’d…
$cal 08 2020
August 2020
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
ROOT: THE SYSTEM ADMINISTRATOR’S LOGIN

The unix system provides a special login name for the exclusive
use of the administrator it is called root.
This account doesn’t need to be separately created but comes
with every system. Its password is generally set at the time of
installation of the system and has to be used on logging in.
The job of system administration involves the management of
the entire system- ranging from maintaining user accounts,
security and managing disk space to performing backups.
Cont’d…
1. Becoming the super user at login time:
eg) Login: root
Password: ********* [Enter]
#-
The prompt of root is #
Once you login as a root you are placed in root’s home directory.
Depending on the system, this directory could be / or /root.
Administrative commands are resident in /sbin and /usr/sbin in
modern systems and in older system it resides in /etc.
Roots PATH list includes detailed path:
For example: /sbin:/bin:/usr/sbin:/usr/bin:/usr/dt/bin
Cont’d…
2. Becoming the super user using su command .
Any user can acquire superuser status with the su command if
they know the root password.
Eg) $ su
Password: ******** #Password of root user
#_
FLEXIBILITY OF COMMAND USAGE

The UNIX system provides certain degree of flexibility in the


usage of commands.
A command can often be entered in more than one way.
Shell allow the following type of command usage:
1. Combining Commands.
2. A command line can overflow or Be split into multiple lines.
3. Entering a command before previous command has finished .
1. Combining Commands
UNIX allows you to specify more than one command in the single
command line.
Ex: $wc sample ; ls –l sample
Or
$(wc sample ; ls –l sample)
Or
$wc sample && ls –l sample
1 3 18 sample
-rw-r--r-- 1 user user 18 Sep 8 05:37 sample
Cont’d…
Or
Two commands combined using filter(|)
$ls | wc
13 13 123
2. A Command Line can Overflow or Be split into Multiple Lines
UNIX terminal width is restricted to maximum 80 characters.
Shell allows command line to overflow or be split into multiple lines.
Ex:
$echo “This is # $ first prompt
>a three-line # > Second prompt
>text message” #Command line ends Output:
This is
a three-line
text message
3. Entering a Command Before Previous Command Has Finished :
When you run a long program, the prompt won't appear until
program execution is complete.
Subsequent commands can be entered at the keyboard without
waiting for prompt.
The input remains stored in a buffer maintained by kernel for all
keyboard input.
The command is passed on to the shell for interpretation after
the previous program has completed.
Unix files
Naming files: The file is a container for storing information.
$cat>foo
ABC
The above file foo will contain only the string ABC and nothing
else.
Unix file doesn’t contain the eof (end of file)mark.
Rules for naming file and directory
names:
1. All file names are case sensitive.
2. You can use upper and lowercase letters, numbers, “.” (dot),
and “_” (underscore) symbols.
3. You can use other special characters(except the /, the NULL
character) such as blank space, but they are hard to use and it
is better to avoid them.
Cont’d…
Eg) .last_time
list.
-{}[]
@#$%abcd
a.b.c.d
Basic file types:
1)Regular file(Ordinary file).
2)Directory file.
3)FIFO file.
4)Device file.
5)Symbolic link file.
1) Regular file
It contains only data as a stream of characters.
An ordinary file can be divided into 2 types:
a) Text file
b) Binary file
a) Text File
It Contains only printable characters.
Or
A text file contains lines of characters where every line is
terminated with the newline character, also known as
linefeed (LF).
When you press[Enter] while inserting text, the LF character
is appended to every line.
Ex: All C/C++ program sources, Shell and perl scripts are text files.
b) Binary file
It contains both printable and unprintable characters that
cover the entire ASCII range(0-255).
Ex: Unix commands, the object and executable files that you
produce by compiling C programs, Picture, sound and video
files are binary files.
This Regular file can be created , browsed through , and
modified by various means such as text editors or compilers.
They can be removed by rm command.
2) Directory file
It is simply a folder where you store filenames and other directories.
A directory file contains an entry for every file and subdirectory that
it houses.
For example: if you have 10 files in a directory means, there will be
10 entries in the directory.
Each entry has 2 components:
i. The filename
ii. A unique identification number in the directory
(called the inode number).
Cont’d…
A directory may be created in Unix by the mkdir command:
Ex: $ mkdir xyz
A directory can be removed via rmdir command:
Ex: $ rmdir xyz
3) FIFO file
It is a special pipe device file which provides a temporary buffer for
two or more processes to communicate by writing data to and
reading data from the buffer(PIPE_BUF).
A fifo file(pipe device file) may be created in Unix by the mkfifo
command:
Ex: $ mkfifo xyz
$ ls –l xyz
A fifo file(pipe device file) may be removed like ordinary file in Unix by
the rm command:
Ex: $ rm xyz
4) Device files (Special files)
Used to represent a real physical device such as a printer,
tape drive or terminal, used for Input/output (I/O) operations.
Based on I/O operations, this file can be divided into 2 types:
i) character device file
ii) block device file.
Note: Device files are stored under /dev and these files don’t
occupy space on disk.
i) Character device file
It represents a physical device that transmits data in
a character-based manner.
Ex: Line printers, modems and consoles etc.
Creating Character Device Files
A character device file is created in Unix via the mknod
command:
Ex: $ mknod /dev/cdf c 115 5

Here a major number refers to a type of device and a minor


number specifies a particular device of that type or
sometimes the operation mode of that device type.
ii) Block device file
It represents a physical device that transmits data a block at a time.
Ex: Hard disk drives and floppy disk drives etc.

A block device file is created in Unix via the mknod command:


Ex: $mknod /dev/bdf b 120 10
5) Symbolic link file
It contains a path name which references another file in either
the local or a remote file system.
A symbolic link file may be created in UNIX via the ln command:
Ex: $ ln –s existing_file new_file
$ ln –s sample1 slink
$ cat –n slink
$ ls –l slink
lr- - r- - r - - 1 user metal 7 Sep 16, 2020 slink->sample1
THE PARENT-CHILD RELATIONSHIP
Cont’d…
The files in UNIX are related to one another.
The file system in UNIX is a collection of all of these file (ordinary, directory and
device , pipe device and symbolic link files) organized in a hierarchical (an inverted
tree) structure as shown in above figure.
The feature of UNIX file system is that there is a top, which serves as the
reference point for all files.
This top is called root and is represented by a / (Front slash).
The root is actually a directory.
The root directory (/) has a number of subdirectories under it.
The subdirectories in turn have more subdirectories and other files under them.
Every file apart from root, must have a parent, and it should be possible to
trace the ultimate parentage of a file to root.
In parent-child relationship, the parent is always a directory.
Cont’d…

pwd - print working directory


At any time you can determine where you are in the file
system hierarchy with the pwd command.
Example:
$ pwd
/home/kumar
Relative and Absolute pathnames:
An absolute path is defined as specifying the location of a file or
directory from the root directory(/).
In other words, we can say that an absolute path is a complete
path from start of actual file system from / directory.
Relative path is defined as the path related to the present working
directly(pwd). It starts at your current directory and never starts
with a /.
Cont’d…
Suppose if we are looking for foo then absolute path for it will be
provided as /home/mthomas/class_stuff/foo
but assuming that we are already present in class_stuff directory
then the relative path for the same can be written as simple foo.
$ date /*Relative Path*/
Mon Sep 21 10:33:14 UTC 2020
$ /bin/date /*Absolute Path*/
Mon Sep 21 10:33:27 UTC 2020
Using . and .. in Relative Path-names:
A relative path-name uses one of following cryptic symbols:
.(a single dot)-this represents the current directory.
..(two dots)-this represents the parent directory.

Example: Suppose we are currently in directory /home/kumar/abc


and now you can use .. as an argument to cd to move to the parent
directory /home/kumar as :
$pwd
/home/kumar/abc
Cont’d…
$cd .. /*moves one level up*/
$pwd
/home/kumar
Now / when used with .. has a different meaning , instead of
moving down a level , it moves one level up:
$pwd
/home/kumar/abc
$cd ../.. /*moves two level up*/
$pwd
/home
The HOME VARIABLE: HOME
DIRECTORY:

When you logon to the system, UNIX places you in a directory


called home directory.
It is created by the system when the user account is created.
If a user login using the login name kumar , user will land up in a
directory that could have the path name /home/kumar.

The shell variable HOME knows the home directory.


$echo $HOME
/home/kumar
cd: CHANGING THE CURRENT DIRECTORY
User can move around the UNIX file system using cd (change
directory) command.
When used with the argument, it changes the current directory to
the directory specified as argument, progs:
$ pwd
/home/kumar
$cd progs
$ pwd
/home/kumar/progs
$cd /bin
$ pwd
/bin
Cont’d…
cd can also be used without arguments:
$ pwd
/home/kumar/progs
$cd (cd without argument changes the working directory to
home directory.)
$ pwd
/home/kumar
$cd /home/sharma
$ pwd
/home/sharma
$cd
/home/kumar
mkdir: MAKING DIRECTORIES
Directories are created with mkdir (make directory) command. The
command is followed by names of the directories to be created. A
directory abc is created under current directory like this:
$mkdir abc
You can create a number of subdirectories with one mkdir
command:
$mkdir abc dba doc
For instance the following command creates a directory tree:
$mkdir progs progs/cprogs progs/javaprogs
This creates three subdirectories – progs, cprogs and javaprogs
under progs.
The order of specifying arguments is important. You cannot create
subdirectories before creation of parent directory.
Cont’d…
For instance following command doesn‘t work
$mkdir progs/cprogs progs/javaprogs progs
mkdir: Failed to make directory “progs/cprogs”; No such
directory
mkdir: Failed to make directory “progs/javaprogs”; No such
directory
System refuses to create a directory due to fallowing reasons:
The directory is already exists.
There may be ordinary file by that name in the current directory.
User doesn‘t have permission to create directory.
rmdir: REMOVING A DIRECTORY

The rmdir (remove directory) command removes the directories.


You have to do this to remove progs:
$rmdir progs
If progs is empty directory then it will be removed from system.
rmdir expect the arguments reverse of mkdir.
Following command used with mkdir fails with rmdir
$mkdir progs progs/cprogs progs/javaprogs
rmdir: directory “progs”: Directory not empty
First subdirectories need to be removed from the system then
parent.
Cont’d…
rmdir : Things to remember

You can‘t remove a directory which is not empty


You can‘t remove a directory which doesn‘t exist in system.
You can‘t remove a directory if you don‘t have permission to do so.
File Related Commands:
1) cat
2) mv
3) rm
4) cp
5) wc
6) od
1) cat: DISPLAYING AND CREATING FILES
Syntax: cat [OPTION]…[FILE]
Example:1) Create file1 with entered content.
$ cat > file1
Hello
^D
Usage of cat Command
1) List contents of file1 on stdout:
$cat file1
2) List the contents of file1 and file2 together on stdout:
$ cat file1 file2
3) Copy contents of file1 and file2 to file3:
$ cat file1 file2 > file3
4)Append contents of file1 and file2 to file4:
$ cat file1 file2 >> file4
The cat command also supports the following options

cat -n: number the output lines.


cat -s: suppress repeated output lines that are empty.
cat –E : display $ at end of each line.
cat –v : Nonprinting ASCII characters can be displayed with –v option.
2) mv: RENAMING FILES
Syntax: mv [OPTION] source destination
The mv command renames (moves) files.
The main two functions are:
1. It renames a file(or directory)
2. It moves a group of files to different directory
It doesn't create a copy of the file; it merely renames it.
No additional space is consumed on disk during renaming.
Example
To rename the file cse as ise we can use the following
command
$mv cse ise
If the destination file doesn‘t exist in the current
directory, it will be created. Or else it will just rename
the specified file in mv command.
A group of files can be moved to a directory.
Ex: Moves three files ch1, ch2, ch3 to the directory module.
$mv ch1 ch2 ch3 module
3) rm : DELETING FILES
Syntax: rm [OPTION]…[FILE]
The rm command deletes one or more files.
Ex: Following command deletes three files:
$ rm mod1 mod2 mod3
To remove all file in a directory, use *
$ rm *
rm options
Interactive Deletion (-i) : Ask the user confirmation before
removing each file:

$ rm -i ch1 ch2
rm : remove ch1 (yes/no)? ? y [Enter ]
rm : remove ch2 (yes/no)? ? n [Enter ]

A ‘y‘ removes the file (ch1) any other response like n or any
other key leave the file undeleted
Recursive deletion (-r or -R): It performs a recursive search for all
directories and files within these subdirectories. At each stage it
deletes everything it finds.

$rm -r *
It deletes all files in the current directory and all its subdirectories.
4) cp : COPYING A File
Syntax: cp [OPTION] source destination
Example: Copies the contents from file1 to file2 and
contents of file1 is retained.
$cp file1 file2
If the destination file (file2) doesn‘t exist, it will first be
created before copying takes place. If not it will simply be
overwritten without any warning from the system.
cp options
Interactive Copying(-i) : The –i option warns the user before
overwriting the destination file, If unit1 exists, cp prompts
for response.
$cp -i ch1 unit1
cp: overwrite unit1 (yes/no)? Y
A ‘y’ at this prompt overwrites the file, any other response
leaves it uncopied.
5) wc: COUNTING LINES, WORDS AND CHARACTERS
The syntax of wc command as shown below:
$wc [options] filenames
wc command performs Word counting including counting of lines and
characters in a specified file. It takes one or more filename as
arguments and displays a four columnar output.
$ wc ofile
4 20 97 ofile
Line: any group of characters not containing a newline.
Word: group of characters not containing a space, tab or newline.
Character: smallest unit of information, and includes a space, tab and
newline.
wc options
wc –l : counts only number of lines.
wc –w: counts only number of words.
wc –c: counts only number of characters.
For multiple filenames, wc produces a line for each file, as well as
a total count.
$wc -c ofile file
97 ofile
15 file
112 total
6) od: DISPLAYING DATA IN OCTAL
od command displays the contents of executable files in a
ASCII octal value.
Ex) $cat > ofile
this file is an example for od command
^d used as an interrupt key
od options:
-b option displays this value for each character separately.
Each line displays 16 bytes of data in octal, preceded by the offset in
the file of the first byte in the line.
$od –b ofile
0000000 164 150 151 163 040 146 151 154 145 040 151 163 040 141 156 040
0000020 145 170 141 155 160 154 145 040 146 157 162 040 157 144 040 143
0000040 157 155 155 141 156 144 012 136 144 040 165 163 145 144 040 141
0000060 163 040 141 156 040 151 156 164 145 162 162 165 160 164 040 153
0000100 145 171
-c option: it shows the printable characters and its corresponding
ASCII octal representation.
Example:
$od –bc ofile
0000000 164 150 151 163 040 146 151 154 145 040 151 163 040 141 156 040
T h i s f i l e i s a n
0000020 145 170 141 155 160 154 145 040 146 157 162 040 157 144 040 143
e x a m p l e f o r o d c
0000040 157 155 155 141 156 144 012 136 144 040 165 163 145 144 040 141
o m m a n d \n ^ d u s e d a
0000060 163 040 141 156 040 151 156 164 145 162 162 165 160 164 040 153
s a n i n t e r r u p t k
0000100 145 171
e y
END OF
MODULE 1

You might also like