Unix Module 12
Unix Module 12
CREDITS – 04
Understand the UNIX Architecture, File systems and use of basic Commands.
Use of editors and Networking commands.
Understand Shell Programming and to write shell scripts.
Understand and analyze UNIX System calls, Process Creation, Control & Relationship.
Module -1 Teaching
Hours
Introduction, Brief history. Unix Components/Architecture. Features of Unix. The UNIX Environment
and UNIX Structure, Posix and Single Unix specification. The login prompt. General features of Unix
commands/ command structure. Command arguments and options. Understanding of some basic 10Hours
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 man
command knowing more about Unix commands and using Unix online manual pages. The man with
keyword option and whatis. The more command and using it with other commands. Knowing the user
terminal, displaying its characteristics and setting characteristics. Managing the non-uniform behaviour
of terminals and keyboards. The root login. Becoming the super user: su command. The /etc/passwd and
/etc/shadow files. Commands to add, modify and delete users.
Topics from chapter 2 , 3 and 15 of text book 1,chapter 1 from text book
Module -2
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 10Hours
.
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. File attributes and permissions and knowing them. The ls command with
options. Changing file permissions: the relative and absolute permissions changing methods.
Recursively changing file permissions. Directory permissions.
The vi editor. Basics. The .exrc file. Different ways of invoking and quitting vi. Different modes of vi.
Input mode commands. Command mode commands. The ex mode commands. Illustrative examples
Navigation commands. Repeat command. Pattern searching. The search and replace command. The set, 10Hours
map and abbr commands. Simple examples using these commands.
The shells interpretive cycle. Wild cards and file name generation. Removing the special meanings of
wild cards. Three standard files and redirection. Connecting commands: Pipe. Splitting the output: tee.
Command substitution. Basic and Extended regular expressions. The grep, egrep. Typical examples
involving different regular expressions.
Topics from chapters 7, 8 and 13 of text book 1. Topics from chapter 2 and 9 ,10 of text book 2
Module-4
Shell programming. Ordinary and environment variables. The .profile. Read and readonly commands.
Command line arguments. exit and exit status of a command. Logical operators for conditional
execution. The test command and its shortcut. The if, while, for and case control statements. The set and 10Hours
shift commands and handling positional parameters. The here ( << ) document and trap command.
Simple shell program examples. File inodes and the inode structure. File links – hard and soft links.
Filters. Head and tail commands. Cut and paste commands. The sort command and its usage with
different options. The umask and default file permissions. Two special files /dev/null and /dev/tty.
Topics from chapter 11, 12, 14 of text book 1,chapter 17 from text book2
.
Module-5
Meaning of a process. Mechanism of process creation. Parent and child process. The ps command with
its options. Executing a command at a specified point of time: at command. Executing a command
periodically: cron command and the crontab file.. Signals. The nice and nohup commands. Background 10Hours
processes. The bg and fg command. The kill command. The find command with illustrative example.
Structure of a perl script. Running a perl script. Variables and operators. String handling functions.
Default variables - $_ and $. – representing the current line and current line number. The range operator.
Chop() and chomp() functions. Lists and arrays. The @- variable. The splice operator, push(), pop(),
split() and join(). File handles and handling file – using open(), close() and die () functions.. Associative
arrays – keys and value functions. Overview of decision making loop control structures – the foreach.
Regular expressions – simple and multiple search patterns. The match and substitute operators.
Defining and using subroutines.
Topics from chapter 9 and 19 of text book 1. Topics from chapter 11 of reference book 1
Course outcomes:
1. Engineering Knowledge
2. Environment and Sustainability
3. Design/Development of Solutions
Question paper pattern:
Text Books:
1. Sumitabha Das., Unix Concepts and Applications., 4th Edition., Tata McGraw Hill
2. Behrouz A. Forouzan, Richard F. Gilberg : UNIX and Shell Programming- Cengage Learning – India
Edition. 2009.
Reference Books:
Introduction
This chapter introduces you to the UNIX operating system. We first look at what is an
operating system and then proceed to discuss the different features of UNIX that have
made it a popular operating system.
Objectives
What is an operating system (OS)?
Features of UNIX OS
A Brief History of UNIX OS, POSIX and Single Unix Specification (SUS)
For example, an OS ensures safe access to a printer by allowing only one application
program to send data directly to the printer at any one time. An OS encourages efficient
use of the CPU by suspending programs that are waiting for I/O operations to complete to
make way for programs that can use the CPU more productively. An OS also provides
convenient abstractions (such as files rather than disk locations) which isolate
application programmers and users from the details of the underlying hardware.
User Applications
Processor/Hardware
UNIX Operating system allows complex tasks to be performed with a few keystrokes. It
doesn’t tell or warn the user about the consequences of the command.
Kernighan and Pike (The UNIX Programming Environment) lamented long ago that ―as
the UNIX system has spread, the fraction of its users who are skilled in its application has
decreased.‖ However, the capabilities of UNIX are limited only by your imagination.
Ken Thompson then teamed up with Dennis Ritchie, the author of the first C compiler in
1973. They rewrote the UNIX kernel in C - this was a big step forwards in terms of the
system's portability - and released the Fifth Edition of UNIX to universities in 1974. The
Seventh Edition, released in 1978, marked a split in UNIX development into two main
branches: SYSV (System 5) and BSD (Berkeley Software Distribution). BSD arose from
the University of California at Berkeley where Ken Thompson spent a sabbatical year. Its
development was continued by students at Berkeley and other research institutions.
SYSV was developed by AT&T and other commercial companies. UNIX flavors based
on SYSV have traditionally been more conservative, but better supported than BSD-
based flavors.
Until recently, UNIX standards were nearly as numerous as its variants. In early
days, AT&T published a document called System V Interface Definition (SVID).
X/OPEN (now The Open Group), a consortium of vendors and users, had one too, in
the X/Open Portability Guide (XPG). In the US, yet another set of standards, named
Portable Operating System Interface for Computer Environments (POSIX), were
developed at the behest of the Institution of Electrical and Electronics Engineers
(IEEE).
In 1998, X/OPEN and IEEE undertook an ambitious program of unifying the two
standards. In 2001, this joint initiative resulted in a single specification called the
Single UNIX Specification, Version 3 (SUSV3), that is also known as IEEE
1003.1:2001 (POSIX.1). In 2002, the International Organization for Standardization
(ISO) approved SUSV3 and IEEE 1003.1:2001.
Some of the commercial UNIX based on system V are:
IBM's AIX
Hewlett-Packard's HPUX
SCO's Open Server Release 5
Silicon Graphics' IRIS
DEC's Digital UNIX
Sun Microsystems' Solaris 2
3. Features of UNIX OS
Several features of UNIX have made it popular. Some of them are:
Portable
UNIX can be installed on many hardware platforms. Its widespread use can be traced to
the decision to develop it using the C language.
Multiuser
The UNIX design allows multiple users to concurrently share hardware and software
Multitasking
UNIX allows a user to run more than one program at a time. In fact more than one
program can be running in the background while a user is working foreground.
Networking
While UNIX was developed to be an interactive, multiuser, multitasking system,
networking is also incorporated into the heart of the operating system. Access to another
system uses a standard communications protocol known as Transmission Control
Protocol/Internet Protocol (TCP/IP).
Device Independence
UNIX treats input/output devices like ordinary files. The source or destination for file
input and output is easily controlled through a UNIX design feature called redirection.
Utilities
UNIX provides a rich library of utilities that can be use to increase user productivity.
Unix Architecture
Users
Shell
Kernel
Hardware
System Calls
UNIX architecture comprises of two major components viz., the shell and the kernel. The
kernel interacts with the machine’s hardware and the shell with the user.
The kernel is the core of the operating system. It is a collection of routines written in C. It
is loaded into memory when the system is booted and communicates directly with the
hardware. User programs that need to access the hardware use the services of the kernel
via use of system calls and the kernel performs the job on behalf of the user. Kernel is
also responsible for managing system’s memory, schedules processes, decides their
priorities.
The shell performs the role of command interpreter. Even though there’s only one kernel
running on the system, there could be several shells in action, one for each user who’s
logged in. The shell is responsible for interpreting the meaning of metacharacters if any,
found on the command line before dispatching the command to the kernel for execution.
A process is the second abstraction UNIX provides. It can be treated as a time image of
an executable file. Like files, processes also belong to a hierarchical structure. We will be
discussing the processes in detain in a subsequent chapter.
2. Locating Files
All UNIX commands are single words like ls, cd, cat, etc. These names are in lowercase.
These commands are essentially files containing programs, mainly written in C. Files are
stored in directories, and so are the binaries associated with these commands. You can
find the location of an executable program using type command:
$ type ls
ls is /bin/ls
This means that when you execute ls command, the shell locates this file in /bin directory
and makes arrangements to execute it.
The Path
The sequence of directories that the shell searches to look for a command is specified in
its own PATH variable. These directories are colon separated. When you issue a
command, the shell searches this list in the sequence specified to locate and execute it.
4. Command Structure
UNIX commands take the following general form:
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. A contiguous string of spaces and tabs together is called
a whitespace. The shell compresses multiple occurrences of whitespace into a single
whitespace.
Options
An option is preceded by a minus sign (-) to distinguish it from filenames.
Example: $ ls –l
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 compined
with only one – sign. i.e., instead of using
$ ls –l –a –t
we can as well use,
$ ls –lat
Because UNIX was developed by people who had their own ideas as to what options
should look like, there will be variations in the options. Some commands use + as an
option prefix instead of -.
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.
Example: cp file1 file2 file3 dest_dir
rm file1 file2 file3
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.
Exceptions
Some commands in UNIX like pwd do not take any options and arguments. Some
commands like who may or may not be specified with arguments. The ls command can
run without arguments (ls), with only options (ls –l), with only filenames (ls f1 f2), or
using a combination of both (ls –l f1 f2). Some commands compulsorily take options
(cut). Some commands like grep, sed can take an expression as an argument, or a set of
instructions as argument.
Combining Commands
Instead of executing commands on separate lines, where each command is processed and
executed before the next could be entered, UNIX allows you to specify more than one
command in the single command line. Each command has to be separated from the other
by a ; (semicolon).
wc sample.txt ; ls –l sample.txt
You can even group several commands together so that their combined output is
redirected to a file.
(wc sample.txt ; ls –l sample.txt) > newfile
When a command line contains a semicolon, the shell understands that the command on
each side of it needs to be processed separately. Here ; is known as a metacharacter.
Note: When a command overflows into the next line or needs to be split into multiple
lines, just press enter, so that the secondary prompt (normally >) is displayed and you can
enter the remaining part of the command on the next line.
A pager is a program that displays one screenful information and pauses for the user to
view the contents. The user can make use of internal commands of the pager to scroll up
and scroll down the information. The two popular pagers are more and less. more is the
Berkeley’s pager, which is a superior alternative to original pg command. less is the
standard pager used on Linux systems. less if modeled after a popular editor called vi and
is more powerful than more as it provides vi-like navigational and search facilities. We
can use pagers with commands like ls | more. The man command is configured to work
with a pager.
7. Understanding The man Documentation
The man documentation is organized in eight (08) sections. Later enhancements have
added subsections like 1C, 1M, 3N etc.) References to other sections are reflected as SEE
ALSO section of a man page.
When you use man command, it starts searching the manuals starting from section 1. If it
locates a keyword in one section, it won’t continue the search, even if the keyword occurs
In another section. However, we can provide the section number additionally as argument
for man command.
For example, passwd appears in section 1 and section 4. If we want to get documentation
of passwd in section 4, we use,
$ man 4 passwd OR $ man –s4 passwd (on Solaris)
A man page is divided into a number of compulsory and optional sections. Every
command doesn’t need all sections, but the first three (NAME, SYNOPSIS and
DESCRIPTION) are generally seen in all man pages. NAME presents a one-line
introduction of the command. SYNOPSIS shows the syntax used by the command and
DESCRIPTION provides a detailed description.
Note: You can use man command to view its own documentation ($ man man). You can
also set the pager to use with man ($ PAGER=less ; export PAGER). To understand
which pager is being used by man, use $ echo $PAGER.
Keystroke Function
or
command
[Ctrl-h] Erases text
[Ctrl-c] or Interrupts a command
Delete
[Ctrl-d] Terminates login session or a program that expects its input from
keyboard
[Ctrl-s] Stops scrolling of screen output and locks keyboard
[Ctrl-q] Resumes scrolling of screen output and unlocks keyboard
[Ctrl-u] Kills command line without executing it
[Ctrl-\] Kills running program but creates a core file containing the memory
image of the program
[Ctrl-z] Suspends process and returns shell prompt; use fg to resume job
[Ctrl-j] Alternative to [Enter]
[Ctrl-m] Alternative to [Enter]
stty sane Restores terminal to normal status
Since ls is a program or file having an independent existence in the /bin directory (or /usr/bin), it
is branded as an external command. Most commands are external in nature, but there are some
which arc not really found anywhere; and some which are normally not executed even if they are
in one of the directories specified by PATH. Take for instance the echo command:
$ type eeho
echo is a shell builtin
echo isn't an external command in the sense that, when you type echo, the shell won't look in its
PATH to locate it (even if it is there in fbi n). Rather, it will execute it from its own set of built-in
commands that arc not stored as separate tiles. These built-in commands, of which echo is a member, are
known as internal commands.
This program starts running for you when you log in, and dies when you log out. The shell is an
external command with a difference; it possesses its own set of internal commands. So if a command
exists both as an internal command of the shell as well as an external one (in /bin or /usr/bin), the
shell will accord top priority to its own internal command of the same name.
What you need to keep in mind is something that beginners often forget-the necessity of
providing spaces between the command and argument. If you have used DIR/P instead of DIR
IP in DOS, don't expect UNIX to be equally accommodating:
S 1s-1
bash: Is-1: command not found
Options can normally be combined with only one - sign, i.e., instead of
using
Is -1 -a -t
Is -lat Same as 1s -I -a - t
to obtain the same output. This facility reduces your typing load, which becomes significant
when you use commands with several options. The command parses (breaks up) the option
combination into separate options.
Because UNIX was developed by people who had their own ideas as to what options should look like,
there will invariably be exceptions [0 whatever rules we try to formulate. Some commands won't let
you combine options in the way you did just now. There are some that use + as an option prefix instead
of -.-. Some even use the =1
12. Basic Commands
Cal :
You can invoke the cal command to see the calendar of any specific month or a complete year. The
facility is totally accurate and takes into account the leap year adjustments that took place in the
year 1752. Let's have a look at its syntax drawn from the Solaris man page:
$ cal 2 2015
February 2015
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
Date :
To display or change the date.
'date' with no arguments prints the current time and date, in the format of the %c directive (described
below). If given an argument that starts with a +, date prints the current time and date (or the time and date
specified by the --date option, see below) in the format defined by that argument, which is the same as in the
strftime function.Except for directives, which start with %, characters in the format string are printed
unchanged.
>date
date '+%m-%d-%Y'
01-23-2012
You can format the output of date command by using the %. Here %m for month, %d for day and %Y for
year.
17
[Ctrl-d]
echo:
This command is used in shell scripts to display diagnostic messages on the terminal or to issue prompts for
taking user input. we have used it in two ways:
1. To display a message
Echo was an external command, but all shells have built-in. As escape sequence is generally a two character-
string beginning with a \ . \c is an escape sequence. When this escape sequence is placed at the end of a string
used as an argument to echo, the command interprets the sequence as a directive to place the cursor and
prompt in the same line that displays the output:
\t- A tab which pushes text to the right by eight character positions.
\n- newline
\a- Bell
\b-Backspace
\f-Formfed
\r-Carriage return
\v- vertical tab
Printf:
The printf command provides a method to print preformatted text similar to the printf() system
interface (C function). It's meant as successor for echo and has far more features and possibilities.
Beside other reasons, POSIX has a very good argument to recommend it: Both historical main
flavours of the echo command are mutual exclusive, they collide. A "new" command had to be
invented to solve the issue.
who:
UNIX is a system that can be concurrently used by multiple users, and you might be interested in
knowing the people who are also using' the system like you. Use the who command
$who
$ 1s ehap*
chapOI chap02
chap03
Sometimes, just displaying a list of filenames isn't enough; you need to know more about these
files. For that to happen, 15 bas to be used with an option, -1, between the command and filenames:
$ls -l
-rw-r--r-- 1 kumar users 5609 Apr 23 09:30 chapO
-rw-r--r-- 1 kumar users 26129 May 14 18:55 chap02
1
-rw-r--r-- 1 kumar users 37385 May 15 10:30 chap03
More command:
The man command displays its output a page at a time. This is possible because it sends its output to a paper
program. Unix have more pager which has replaced pg, the original pager of unix.
more chap01
You can see the content on the screen, one page at a time. At the bottom of the screen, you will also see the
filename and percentage of the file that has been viewed.
--more—(17%)
f or the spacebar
and to move back one page, use b
2. Repeating The Last Command (.) more has a repeat command, the dot (same command used
by vi), that repeats the last command you used. If you scroll forward with lOf, you can scroll
another10 pages by simply pressing a dot. This is a great convenience available in more!
3.Searching pattren
You can perform a search for a pattern with the /command followed by the string. For instance, to
look for the first wh11 e loop in your program, you'll have to enter this:
/while
4.Using more in a Pipeline
The 1s output won't fit on the screen if there are too many files, so the command has to be used like
this:
$ls | more
$uname
Linux
. Linux systems simply show the name L1nux. Using suitable options.
The Current Release (-r) Since UNIX comes in many flavors, vendors have customized a number of
commands to behave in the way they want, and not as AT&T decreed. A UNIX command often
varies across versions so much so that you'll need to use the -r option to find out the version of your
operating system:
$uname –r
5.8
Passwd:
14. /etc/passwd
smithj:x:561:561:Joe Smith:/home/smithj:/bin/bash
Each field in a passwd entry is separated with ":" colon characters, and are as
follows:
Another method of storing account information, one that I always use, is with the
shadow password format. As with the traditional method, this method stores
account information in the /etc/passwd file in a compatible format. However, the
password is stored as a single "x" character (ie. not actually stored in this file). A
second file, called ``/etc/shadow'', contains encrypted password as well as other
information such as account or password expiration values, etc. The /etc/shadow
file is readable only by the root account and is therefore less of a security risk
The ``/etc/shadow'' file contains password and account expiration information for
users, and looks like this:
smithj:Ep6mckrOLChF.:10063:0:99999:7:::
As with the passwd file, each field in the shadow file is also separated
with ":" colon characters, and are as follows:
Introduction
In this chapter we will look at the file system of UNIX. We also look at types of files
their significance. We then look at two ways of specifying a file viz., with absolute
pathnames and relative pathnames. A discussion on commands used with directory files
viz., cd, pwd, mkdir, rmdir and ls will be made. Finally we look at some of the important
directories contained under UNIX file system.
1. Types of files
A simple description of the UNIX system is this:
―On a UNIX system, everything is a file; if something is not a file, it is a process.‖
A UNIX system makes no difference between a file and a directory, since a directory is
just a file containing names of other files. Programs, services, texts, images, and so forth,
are all files. Input and output devices, and generally all devices, are considered to be files,
according to the system.
Most files are just files, called regular files; they contain normal data, for example text
files, executable files or programs, input for or output from a program and so on.
While it is reasonably safe to suppose that everything you encounter on a UNIX system is
a file, there are some exceptions.
Directories: files that are lists of other files.
Special files or Device Files: All devices and peripherals are represented by files. To read
or write a device, you have to perform these operations on its associated file. Most
special files are in /dev.
Links: a system to make a file or directory visible in multiple parts of the system's file
tree.
(Domain) sockets: a special file type, similar to TCP/IP sockets, providing inter−process
networking protected by the file system's access control.
Named pipes: act more or less like sockets and form a way for processes to communicate
with each other, without using network socket semantics
Ordinary (Regular) File
This is the most common file type. An ordinary file can be either a text file or a binary
file.
A text file contains only printable characters and you can view and edit them. All C and
Java program sources, shell scripts are text files. Every line of a text file is terminated
with the newline character.
A binary file, on the other hand, contains both printable and nonprintable characters that
cover the entire ASCII range. The object code and executables that you produce by
compiling C programs are binary files. Sound and video files are also binary files.
Directory File
A directory contains no data, but keeps details of the files and subdirectories that it
contains. A directory file contains one entry for every file and subdirectory that it houses.
Each entry has two components namely, the filename and a unique identification number
of the file or directory (called the inode number).
When you create or remove a file, the kernel automatically updates its corresponding
directory by adding or removing the entry (filename and inode number) associated with
the file.
Device File
All the operations on the devices are performed by reading or writing the file representing
the device. It is advantageous to treat devices as files as some of the commands used to
access an ordinary file can be used with device files as well.
Device filenames are found in a single directory structure, /dev. A device file is not really
a stream of characters. It is the attributes of the file that entirely govern the operation of
the device. The kernel identifies a device from its attributes and uses them to operate the
device.
2. Filenames in UNIX
On a UNIX system, a filename can consist of up to 255 characters. Files may or may not
have extensions and can consist of practically any ASCII character except the / and the
Null character. You are permitted to use control characters or other nonprintable
characters in a filename. However, you should avoid using these characters while naming
a file. It is recommended that only the following characters be used in filenames:
Alphabets and numerals.
The period (.), hyphen (-) and underscore (_).
UNIX imposes no restrictions on the extension. In all cases, it is the application that
imposes that restriction. Eg. A C Compiler expects C program filenames to end with .c,
Oracle requires SQL scripts to have .sql extension.
A file can have as many dots embedded in its name. A filename can also begin with or
end with a dot.
UNIX is case sensitive; cap01, Chap01 and CHAP01 are three different filenames that
can coexist in the same directory.
3. Directories and Files
A file is a set of data that has a name. The information can be an ordinary text, a user-
written computer program, results of a computation, a picture, and so on. The file name
may consist of ordinary characters, digits and special tokens like the underscore, except
the forward slash (/). It is permitted to use special tokens like the ampersand (&) or
spaces in a filename.
Unix organizes files in a tree-like hierarchical structure, with the root directory, indicated
by a forward slash (/), at the top of the tree. See the Figure below, in which part of the
hierarchy of files and directories on the computer is shown.
Examples
mkdir patch Creates a directory patch under current directory
mkdir patch dbs doc Creates three directories under current directory
mkdir pis pis/progs pis/data Creates a directory tree with pis as a directory under
the current directory and progs and data as
subdirectories under pis
Note the order of specifying arguments in example 3. The parent directory should be
specified first, followed by the subdirectories to be created under it.
The system may refuse to create a directory due to the following reasons:
1. The directory already exists.
2. There may be an ordinary file by the same name in the current directory.
3. The permissions set for the current directory don’t permit the creation of files and
directories by the user.
E.g.
rmdir patch Directory must be empty
rmdir pis pis/progs pis/data Shows error as pis is not empty. However rmdir
silently deletes the lower level subdirectories progs
and data.
Whenever you enter any UNIX command, you are actually specifying the name of an
executable file located somewhere on the system. The system goes through the following
steps in order to determine which program to execute:
1. Built in commands (such as cd and history) are executed within the shell.
2. If an absolute path name (such as /bin/ls) or a relative path name (such as ./myprog),
the system executes the program from the specified directory.
3. Otherwise the PATH variable is used.
The mode field is given by the -l option and consists of 10 characters. The first character
is one of the following:
CHARACTER IF ENTRY IS A
d directory
- plain file
b block-type special file
c character-type special file
l symbolic link
s socket
The next 9 characters are in 3 sets of 3 characters each. They indicate the file
access permissions: the first 3 characters refer to the permissions for the user,
the next three for the users in the Unix group assigned to the file, and the last 3
to the permissions for other users on the system.
Designations are
as follows:
r read permission
w write permission
x execute permission
- no permission
E
x
a
m
p
l
e
s
1. To list the files in a
directory:
$ ls
2. To list all files in a directory, including the hidden
(dot) files:
$ ls -a
3. To get a
long listing:
$
l
s
-
a
l
t
o
t
a
l
2
4
drwxr-sr-x 5 workshop acs 512 Jun 7 11:12 .
drwxr-xr-x 6 root sys 512 May 29 09:59 ..
-rwxr-xr-x 1 workshop acs 532 May 20 15:31 .cshrc
-rw------- 1 workshop acs 525 May 20 21:29 .emacs
-rw------- 1 workshop acs 622 May 24 12:13 .history
-rwxr-xr-x 1 workshop acs 238 May 14 09:44 .login
-rw-r--r-- 1 workshop acs 273 May 22 23:53 .plan
-rwxr-xr-x 1 workshop acs 413 May 14 09:36 .profile
-rw------- 1 workshop acs 49 May 20 20:23 .rhosts
drwx------ 3 workshop acs 512 May 24 11:18
demofiles drwx------ 2 workshop acs 512
May 21 10:48 frank
drwx------ 3 workshop acs 512 May 24 10:59 linda
Directory Content
/bin Common programs, shared by the system, the system administrator and the users.
Contains references to all the CPU peripheral hardware, which are represented as files with
/dev
special properties.
Most important system configuration files are in /etc, this directory contains data similar to
/etc
those in the Control Panel in Windows
/home Home directories of the common users.
/lib Library files, includes files for all kinds of programs needed by the system and the users.
/sbin Programs for use by the system and the system administrator.
Temporary space for use by the system, cleaned upon reboot, so don't use this for saving any
/tmp
work!
/usr Programs, libraries, documentation etc. for all user-related programs.
Storage for all variable files and temporary files created by users, such as log files, the mail
/var queue, the print spooler area, space for temporary storage of files downloaded from the
Internet, or to keep an image of a CD before burning it.
File Attributes
ls command is used to obtain a list of all filenames in the current directory. The
output in UNIX lingo is often referred to as the listing. Sometimes we combine this
option with other options for displaying other attributes, or ordering the list in a different
sequence. ls look up the file’s inode to fetch its attributes. It lists seven attributes of all files
in the current directory and they are:
The file type and its permissions are associated with each file. Links indicate the
number of file names maintained by the system. This does not mean that there are so
many copies of the file. File is created by the owner. Every user is attached to a group
owner. File size in bytes is displayed. Last modification time is the next field. If you
change only the permissions or ownership of the file, the modification time remains
unchanged. In the last field, it displays the file name.
For example,
$ ls –l
total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 1 kumar metal 4174 may 10 15:01 chap02
-rw-rw-rw- 1 kumar metal 84 feb 12 12:30 dept.lst
-rw-r--r-- 1 kumar metal 9156 mar 12 1999 genie.sh
drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs
Directories are easily identified in the listing by the first character of the first
column, which here shows a d. The significance of the attributes of a directory differs a
good deal from an ordinary file. To see the attributes of a directory rather than the files
contained in it, use ls –ld with the directory name. Note that simply using ls –d will not
list all subdirectories in the current directory. Strange though it may seem, ls has no
option to list only directories.
File Ownership
When you create a file, you become its owner. Every owner is attached to a group
owner. Several users may belong to a single group, but the privileges of the group are set
by the owner of the file and not by the group members. When the system administrator
creates a user account, he has to assign these parameters to the user:
The user-id (UID) – both its name and numeric representation
The group-id (GID) – both its name and numeric representation
File Permissions
UNIX follows a three-tiered file protection system that determines a file’s access
rights. It is displayed in the following format:
For Example:
The first group has all three permissions. The file is readable, writable and
executable by the owner of the file. The second group has a hyphen in the middle slot,
which indicates the absence of write permission by the group owner of the file. The third
group has the write and execute bits absent. This set of permissions is applicable to
others.
You can set different permissions for the three categories of users – owner, group
and others. It’s important that you understand them because a little learning here can be a
dangerous thing. Faulty file permission is a sure recipe for disaster
chmod only changes the permissions specified in the command line and leaves the
other permissions unchanged. Its syntax is:
The command assigns (+) execute (x) permission to the user (u), other permissions
remain unchanged.
Let initially,
Then, it becomes
Here, we need not to know the current file permissions. We can set all nine
permissions explicitly. A string of three octal digits is used as an expression. The
permission can be represented by one octal digit for each category. For each category, we
add octal digits. If we represent the permissions of each category by one octal digit, this is
how the permission can be represented:
We have three categories and three permissions for each category, so three octal
digits can describe a file’s permissions completely. The most significant digit represents
user and the least one represents others. chmod can use this three-digit string as the
expression.