Sei sulla pagina 1di 75

VIDYAVAHINI FIRST GRADE COLLEGE

UNIX PROGRAMMING
4th Semester BCA

Vidyavahini First Grade College


Near Puttanjaneya Temple, Kuvempunagar, Tumkur – 572103.
E-Mail:vvfgc.bca@gmail.com
Website:www.vidyavahini.org/bca
Contact No: 0816 – 2261130Contact No: 0816 – 226113
Unix Programming Vidyavahini First Grade College, Tumkur.

Chapter-1

Getting Started With UNIX


This chapter begins the tour of the UNIX universe. To understand UNIX, we will first have to
know what an operating system is, why computer needs operating system and how UNIX is
vastly different from other operating systems that came before and after.

Operating system:

Operating system is the software that manages the computer’s hardware and
provides convenient and safe environment for running programs. It acts as an interface
between programs and the hardware resources.

It is loaded into memory when a computer is booted and remains active as long as
machine is up. After any program has completed execution, the operating system cleans up the
memory and registers and makes them available for the next program.

Modern operating systems are Multiprogramming that is they allow multiple


programs to be in memory.

Like DOS and WINDOWS, there is another operating system called UNIX. It
arrived earlier than other two. UNIX is a gient operating system, and is way ahead of them in sheer
power. It has practically everything an operating system should have, and several features which
other operating systems never had.

The UNIX was pioneered by Ken Thompson and Dennis Ritchie at AT & T Bell Labs in

1960’s.

The design of this operating system was to create an environment that promoted efficient
program development.

The origin of UNIX operating system was MULTICS, it is a time sharing operating system.

The Unix operating system found its beginnings in MULTICS, which stands for Multiplexed
Operating and Computing System. The MULTICS project began in the mid 1960s as a joint
effort by General Electric, Massachusetts Institute for Technology and Bell Laboratories. In 1969
Bell Laboratories pulled out of the project.

Department of BCA Page 2


Unix Programming Vidyavahini First Grade College, Tumkur.

One of Bell Laboratories people involved in the project was Ken Thompson. He liked the
potential MULTICS had, but felt it was too complex and that the same thing could be done in
simpler way. In 1969 he wrote the first version of Unix, called UNICS. UNICS stood for
Uniplexed Operating and Computing System. Although the operating system has changed, the
name stuck and was eventually shortened to Unix.

Ken Thompson teamed up with Dennis Ritchie, who wrote the first C compiler. In 1973 they
rewrote the Unix kernel in C. The following year a version of Unix known as the Fifth Edition
was first licensed to universities. The Seventh Edition, released in 1978, served as a dividing
point for two divergent lines of Unix development. These two branches are known as SVR4
(System V) and BSD (Berkeley software distribution)

Why Use UNIX?

One of the biggest reasons for using UNIX is networking capability. With other operating
systems, additional software must be purchased for networking. With UNIX, networking
capability is simply part of the operating system. UNIX is ideal for such things as worldwide
e-mail and connecting to the Internet.

Knowing Machine

Unlike DOS and Windows, UNIX can be used by several users concurrently. If you have access
to such a multiuser system, then in all probability yo will be sitting with just a terminal or monitor
and a keyboard.

Things are different, however when you are the sole user of the system. This could happen if
you work on a desktop machine that has its own CPU, RAM, hard disk, floppy and CD-ROM
drives, printer and controllers of these devices. If you own machine you are directly responsible
for its start’s up, shut down and maintenance. If you lose a file your job to get it from a back up.

Logging in with Username and Password


UNIX is security conscious and can be used only by those persons who maintain an account with
the computer system. The list of accounts is maintained seperatly in the computer. We can’t
simply sit down at any terminal and start banging away if our name does’nt feature in the list.

Because the system can be used by many users, some one has to be given charge of
administration of the system. This person is known as system administrator, and he is the person
who will grant you authority to use the system. He opens an account with a name for our use, and
gives you a secret code that you have to enter when the system prompts you for it. If you are
running UNIX on your desktop, then remember that you are the administrator of the machine.

3
Unix Programming Vidyavahini First Grade College, Tumkur.

The system shows the $ prompt, with the cursor constantly blinking beside it. This is a typical
UNIX prompt, and many UNIX systems use the $ as the default prompt setting. For some users
you might see the % instead of the $, and the system administrator will use the prompt of #.

Comparision of UNIX and DOS

Department of BCA Page


DOS (disk operating system) is a single user operating system.

• It is not case sensitive.


• It has no mutitasking capability.
• It is only used for the personal computers.

UNIX is a multiuser operating system.

• It is case sensitive.
• It has multitasking capability.
• It supports for server or host system.

Comparing WINDOWS and UNIX

WINDOWS is a user friendly operating system.

• It is a graphical user interface.


• It is a single user operating system.
• It has a registry concept.
• It is a licenced OS, it means we have to be purchased.
• It is easily attacked by virus.
• In this file system architecture will be flat.

UNIX is not a user friendly, it is a command based operating system.

• It is a command line user interface. [CUI] It is a multiuser operating system.


• It does not have a registry concept.
• It is free or open source code. It means if we are downloade the code and then also
edit (insert, delete and modify etc) that code.
• It does not affected by virus.
• In this file system architecture will be hierarchical.

Questions:

Department of BCA Page 4


Unix Programming Vidyavahini First Grade College, Tumkur.

1. What is open source code ? (june-2011 :1 mark) 2.


Who invented UNIX Operating system ?
3. Compare UNIX and DOS. (june-2011:3 marks)
4. Compare WINDOWS and UNIX. (may-2012:3marks)

Chapter-2
UNIX Architecture and Command usage
UNIX Architecture:

UNIX is a powerful system. Before we examine the features of this, we need to understand its
software architecture. UNIX components are

• Hardware
• Kernel
• Shell
• Application programs

These are framed in following way

5
Unix Programming Vidyavahini First Grade College, Tumkur.

Hardware: It is the physical component of the system. it is visible to the user.

Kernel: kernel is the core of the unix operating system. It is loaded into memory when the system
is booted. Kernel directly interacts with the hardware. But it cannot directly interact with the user.

Kernel controls all control resources. Itallocates time and memory for the programs and it will
handles file management system etc. The kernel functions are shown in below

Device drivers

Shell: Shell is an interface between user and the kernel. Shell is known as Command
Interpreter.

Why means suppose we are enter one command at the user prompt at the time kernel
does not interact directly with user. So the Shell will be acivate and take that command searches
code for that. If it succeed in searching then it sends a request to the kernel through system calls
then the kernel will execute that command. This is the purpose shell is known as command
interpreter.

Ex: $ rm myfile

In the above example rm is the command for removing a file. Myfile is the name of the file.

Shell will be searches for the code of rm command. If it suceed that one then kernel will execute
this command. The file myfile will be removed.

Application Programs:

Process
Memory
Department
Dep of BCA
artment of BCA management PagePage
6
management
kernel

File
Unix Programming Vidyavahini First Grade College, Tumkur.

These are the programs operated by the end users.

Ex: DBMS, word processor, spread sheet etc.

Architecture of UNIX system kernel


Unix Kernel architecture also having 3 layers. They are

• User mode
• Kernel mode Hardware

These layers are as shown in below.

Kernel mode mainly controls 2 layers they are

• file system management


process management.

7
Unix
Programming Vidyavahini First Grade College, Tumkur.

UNIX Command Format

Unix has a different Command format. Format will be

$ Verb -option (s) arguments

Here verb name of the command

option it is command modifier. It is preceeded by hypen(-)

symbol. arguments it means name of the file or directory or more

information.

In general:
$ command name -option(s) arguments
Unix comamnd can have multiple options and arguments.

Optiona is an optional thing. This is not a mandatory.

But arguments are mandatory. Some commands are having no arguments.

Department of BCA Page 8


Unix
Programming Vidyavahini First Grade College, Tumkur.

Here command name and the option seperated by space and option and arguments are also seperated
by space. But hyphen and option are not seperated by space.

Ex: $ ls –l this is the correct way.

$ ls-l this is an incorrect way.

Rules to apply Unix Commands:

• All unix commands must be entered in lowercase letters only.


• If multiple options are to be used on a sigle line, they can be combined with a single hyphen.
Ex: $ ls –l-a-t it can also written as
$ ls –lat
• Multiple commands can be given on a single line by seperating with semicolon. Ex: $ ls –l ; wc –
c
• Certain commands can not take any arguments.

Features of UNIX operating system


The UNIX operating system offers several features. They are

• Multiuser Ability
• Mutitasking Ability
• Security
• Communication
• Hierachical file system
• Machine independence

Multiuser Ability:

Unix is a Multiuser operating system. Means one computer resources like hard disk,
memory, printer etc are accessible by many users. That is many users can share the same computer
resources.

Multitasking Ability:

Department of BCA Page 9


Unix
Programming Vidyavahini First Grade College, Tumkur.

It is the ability of carrying more than one job at a time. Means a single user can run
multiple tasks concurrently. For example user edit a file, print another one on the printer, send mail
to a friend and browse also all without leaving any of the applications.

In a multitasking environment, a user sees one job running in the foreground, the rest run in
the background.

Security:

Unix provides excellent security feature for protecting the data.

There are 3 types of security levels. They are


User level: In this level every user of unix is provided user name and password to ensure that only
authorized users can access that system.

File level: In this level every user give the permission to the files like read, write and execute. These
permissions can be changed by the user.

Text level: In this we were used encryption tecnique by using crypt command. By using this we
are converting readable format data into unreadable format. If some one succeeds opening our file
the contents of that file will be safe.

Hierarchical File System:

Unix system uses a hierachical file structure to store the information. This structure has
maximum flexibility and easy to understand and easy way to maintain.

Machine Independence:

The unix system hides the machine architecture from the user. It will be easier to write
the applications. Those are run on another machines.

General Commands

cal: (to display calendar of the specific month or year)


This command can be used to display calender of any specific month or year. The facility is totally
accurate and takes arguments as month and year.

Syntax: $ cal [month] [year]

The cal command with out take any argument it will display present month of the calender. But if
it takes any arguments as month and the year then it will display that specific calender only.

Department of BCA Page 10


Unix
Programming Vidyavahini First Grade College, Tumkur.

Syntax: $ cal 03 2013

It will display march month calender in 2013

Syntax: $ cal

Calender command canot take any arguments it will display present month of the calender.

date: (to display date and time)


date is the command used to display current date with time and nearest seconds also.

Syntax: $date -option(format specifies)


• Here we want to get desired output then we will use format specifiers along with the date
command.
• Those format specifies must be preceded by + symbol.
• When multiple format specifiers are used they must be enclosed with in double quotes are
preceded by + symbol.

Format Specifier purpose

+%d it will be display the day of the month.(1-31) +%y

it will display the last two digits in year.

+%m it will display the present month number.

+%h it will display the present month name.

+”%H%M%S” it will display the hour, minute and seconds.

+%D it will display date format like mm/dd/yy +%T

it will display time format like hh:mm:ss

echo: (to display a message)


This is the command used to display the message on the screen. That message may or may not enclosing
with in quotes.

Syntax: $ echo –option string

Department of BCA Page 11


Unix
Programming Vidyavahini First Grade College, Tumkur.

Ex: $ echo

It will display a blank line.

Ex2:$ echo $SHELL

It will display the name of the shell being used.

Ex3: $echo unix programming

Output: unix programming

Ex4: $ echo unix programming

It will display same string but space will be reduced.

Output: unix programming

Ex5: $ echo “unix programming”


It will display string with space

Output: unix programming

printf: (formatted output)


Iit is an alternative way of echo command. Using this printf command display the formatted output.
This is an external command. It can be used as same as the echo command.

Both printf and echo are used same escape sequences Here

we were used format specifiers also.

Syntax: $ printf “formatted string”

Ex: $printf “invalid input\n”

Output: invlaid input.

Ex2: $ printf “current shell is %s\n” $SHELL Output:

Current shell is /bin/bash

Department of BCA Page 12


Unix
Programming Vidyavahini First Grade College, Tumkur.

Ex3: $ printf “the value of 255 is %o in octal and %x in hexa decimal” Output:

The value of 255 is 377 in octal and ff in hexadecimal.

tput: (repositioning the cursor)

tput is the command which is used to repositioning the cursor and also set background color and
foreground colors. Text will be bold and rebold etc.

Syntax: $ tput option [rowno] [colono]

Ex: $ tput cup 10 20

In the above example we were used the arguments of cup and 10 and 20.

10 is the row number

20 is the column number.


In this the cursor will be moved to 10th row and 20th column.

Ex2: $ tput smso

Using this we can bold the text.

Ex3: $ tput rmso

Using this rebold the text.

Ex4: $ tput smul

Using this text will be underlined. To remove that underline rmso is used.

Ex5: $ tput setb colorcode

Using this we can set background color. Color cod is numbers or alphabets or alphanumeric.

Ex6: $ tput setf colorcode

Using this we can set foreground(text) color. Color cod is numbers or alphabets or alphanumeric

bc command (the calculator)

Department of BCA Page 13


Unix
Programming Vidyavahini First Grade College, Tumkur.

Unix provides 2 types of calculators. They are

graphical object (xcalc)

bc

• Compared to bc, xcalc is quite easy to use and it is user friendly, it is graphical
calculatorand visible by user.
• bc command less friendly but extreamly powerful command to perform accurate
caluculations.

Syntax: $ bc

Syntax: $ xcalc

passwd (changing the password)

It is used to change the present password of the system.

Syntax: $passwd

Conditions:
• It can be not too similar to the old password.
• It must be at least 6 characters. It must not be based on dictionary word.

uname (machine’s characteristics)


It will display the features of the operating system running on our machine.

Syntax: $ uname -option

By default it will display the name of the operating system.

Option purpose

-m it prints the machine hardware name.

-r it prints the operating system releasing level.

-n it display the host name.

-s it display the name of the operating system.

Department of BCA Page 14


Unix
Programming Vidyavahini First Grade College, Tumkur.

-v it prints the operating system version.

who (who are the users)

Using this command display the details of active users, time and also process id etc.

Syntax: $ who

It will display following details

Name  it will identify the users login name.

Time  it is the time when the user login.

Pid  it identifies process id

Host name it indicates the name of the machine user login.

who am i (present user)

In this command along with who command two arguments are there they are am and i. both are
predefined arguments. Syntax: $who am i
It will display only one user who has presently work on the system.

tty (terminal details or knowing out terminal)

In Unix even terminals are teated as files. This command is used to display the details about terminals.

In Unix has 7 terminals in command prompt.

Syntax: $ tty

This command has not having any arguments.

man (Unix command manual )


The man command, which is used to get the in-depth knowledge or information about the requested
command.

Department of BCA Page 15


Unix
Programming Vidyavahini First Grade College, Tumkur.

Syntax: $ man –option command name

Ex: $ man cal

This syntax will display the total information about the calendar command.

Questions:

1. Explain echo and who commands. (june-2011:3marks) 2.


Write and explain any 4 features of UNIX operating system.
(june-2011:1mark,june-2010:3marks,may-
2012:3marks)
3. What are the different security levels in UNIX operating system? (june-2011 : 3marks)
4. Explain the usage of a)cal b)date c)who commans. (june-2011:4marks)
5. Explain UNIX session. (june-2011:3marks) 6. What is the diffrence
between argument and the option? (june-2012:3marks)
7. Explain UNIx system architecture with a neat diagram.
(june-2010:7marks, may-2012:7marks)
8. What are the facilities provided by the kernel? (may-2012:3marks)

Chapter-3

Files and Directories


In this chapter, we began our study of one of the two pillars that support UNIX. That is file system.

Unix looks everything treated as a file and any Unix system has thousands of files. Files grow
rapidly, and they are not organized properly, you will find it difficult to locate them. Unix file
system permits to create folders to store files. These folders are known as directories. The File
(Types of files)

A file is container for storing information. we can treat simply file is a sequence of characters.

In Unix files are divided into 3 categories. They are

Department of BCA Page 16


Unix
Programming Vidyavahini First Grade College, Tumkur.

• Ordinary files
• Directory files
• Special or device files

Ordinary files:

These are also known as “regular files”. It is the most common type of the file. All
programs we write belongs to this category.

An ordinary file itself can be divided into 2 types. They are

• Text file
• Binary file

A Text file contains only printable characters. The characteristic feature of text files is that the data
inside them are divided into groups of lines, with each line terminated by the new line character.

A Binary file contains both printable and unprintable characters that covers entire ASCII range (0 to
255). Most Unix commands are binary files.

To identify this ordinary file the first character is hyphen symbol (-).

Directory files:

This is a special type of a file in Unix, which only contains a list of files and directories
also.
We cannot work with these directories directly. A directory file contains 2 fields for each file.

they are name of the file and identification number (inode number). This inode is an unique number
to each file and directory.

When an ordinary is created or removed, its corresponding directory file is automatically updated
by the kernel.

To identify this directory file the first character will be “d”.

Device files:

This type of files are also known as special files. This includes printers, tapes, floppy, CD-
ROM etc. Almost every device has a special file in Unix.

If we want to see those special files or device files then we were use two special directories those are
/dev or /etc.

Department of BCA Page 17


Unix
Programming Vidyavahini First Grade College, Tumkur.

Rules for naming a file


• A filename can consisting of up to 255 characters.
• Files may or may not having extensions.
• A file can have many dots included in its name.
a.b.c.d.e is a valid filename.
• A file can also begin with a dot or end with one dot.
• UNIX is case sensitive. Chap1 and CHAP1 both are different files in unix.
• The file name should never begin with a hyphen(-) symbol. Because it identify an option.

Types of users

The system administrator is primarily responsible for the operation on the system and also creates
different users of the file.

Unix supports 3 types of users. Those are

• File owner (U)


• Group owner (G)
• Others (O)

File owner:

Every file has its owner, he was the person who creates the file. The owner of a file can perform
any type of operation on that file like add, delete etc.

The owner has full control capacity to the accessing of the file at any time.
It is represented by the letter ‘U’.

Group owner:

Suppose we are not the user of owner, the shell will check the member of the group owner.
Whether you are a member of the group or not.

If we are in that group we have to be permitted to control the files.

It is represented by the letter ‘G’.

Others:

Users who are neither file owner nor the meber of group that category is known as others.

Department of BCA Page 18


Unix
Programming Vidyavahini First Grade College, Tumkur.

It is represented by the letter ‘O’.

Types of permissions

Each and every file has 3 types of permissions. They are

• Read (r)
• Write (w)
• Execute (x)

Read:

A user who has read permission for a file can look at the contents of that file.

A user who has read permission for a directory can find out what are the files under that directory.
Read permission is the basic permission of each file and directory.

It is represented by the letter “r” and it is having the permission number “4”.

Write:

A user who has write permission for a file or directory can change the contents or data in file
or directory. In this the user can create a new files and delete and also any type of the
modifications done on them.

It is represented by the letter “w” and it is having the permission number “2”.

Execute:

A user who has execute permission for a file can use that filename as a unix command.
A user who has execute permission for a directory can use that directory name under the root directory.

It is represented by the letter “x” and it is having the number “1”.

Department of BCA Page 19


Unix
Programming Vidyavahini First Grade College, Tumkur.

The above mentioned those are types of files, types of users and types of permissions can be
represented as below. It can be obtained by using “ls” command

$ls –l then the output will be

- rwx r-- r-- 1 aaa user 1024 month &time file or directory name

U G O owner

Ordinary file links of file home directory


d rwx r-- r-- 1

directory file

Handling of Ordinary files cat: (


creating and displaying file)

cat is the one of most well known command in Unix.

This command has three purposes. They are

• Creating a file (>)


• Appending contents to existing file (>>)
• Displaying contents on the file

Creating file:

Cat command is used to create a file by using > (redirection) operator. But using this
command we can create only one file at a time.

Syntax: $ cat > filename

Ex: $ cat > aaa


In the above example we are creating aaa file.

Department of BCA Page 20


Unix
Programming Vidyavahini First Grade College, Tumkur.

Appending contents to existing file:

Using cat command we can append or add content to the existing file. For this purpose
we use >> symbol.

Syntax: $cat >> filename

Ex: $ cat >> aaa

In the above example we are adding some more content to the existing file aaa.

Displaying contents on file:

Using this syntax we can display contents or information on the file.

Syntax: $ cat filename Ex:

$ cat aaa

touch (create multiple files and changing the accessing time)

touch command has 2 purposes. They are

• Creating multiple files

By using this command we can create multiple files at a time. But those files are empty. Means using
touch command we cannot insert data into file. For that purpose we will use one editor like emacs, vi
etc.

Syntax: $ touch filename1 filename2 filename3…..filename n

Ex: $ touch aaa bbb ccc ddd

Using the above example we can create 4 files at a time. But we can not enter data into those files.

At that time use vi filename.

• Changing the time stamp of the file

By using this command we can also change the accessing time of the given file.

Syntax: $ touch -option filename

Department of BCA Page 21


Unix
Programming Vidyavahini First Grade College, Tumkur.

Ex: $ touch –m aaa


Using the above example we can change the time of the file is aaa.

cp (copying contents from one file to another file)


Using this cp command we can copy the contents or information from source file to destination file.

Source file is already created by user. But destination file will create when we are used cp command.

This syntax requires minimum 2 files. In this both files are appeared in our current directory.

Syntax: $ cp sourcefile destinationfile

Ex: $ cp aaa bbb

In the above example we can copy the information from aaa to bbb.

Ex: cp file1 file2 file3 dir1

Using the above syntax we can copy 3 files contents to one directory.

mv (renaming the file)


Using this mv command we can rename the existing file and also we can copy the contents to new
file. But only new file will be appeared in our directory. It can replace old file.

Syntax: $ mv existingfile newfile

Ex: $ mv vvfgc visionvvfgc

In the above example we can rename the file of vvfgc to visionvvfgc.

rm (removing the file)

Using this command we can remove file(s) from current directory. By using this we can remove more
than one file at a time.

Syntax: $ rm filename

By using this syntax we can remove only that particular file.

Syntax: $ rm *

Department of BCA Page 22


Unix
Programming Vidyavahini First Grade College, Tumkur.

By using this syntax we can remove all files in our current directory.

Syntax: $ rm a*
By using this syntax we can remove all files those files are having the starting letter “a”.

ls (list of files and directories)

This command is used to display all files and directories in our current directory.

Syntax: $ ls -option filename

Syntax: $ ls

By using this syntax means ls command it cannot take any arguments and the options it will display
list of files and directories.

Option purpose

-a it display all hidden files.

-d it display only directory name.

-m it display all files and directories separated by


comma.

-i it display all inode numbers of files and directories.

-p it display / after all directories.

-l it display long format of files and directories. -r it display reversed order of file

and directories. wc (count number of words, characters and lines in a file)

By using this command we can display the number of lines, number of words and number of characters
in a particular file.

Syntax: $ wc -option filename

• If wc command cannot take any option it will display number of words, number of
characters and number of lines in a particular file by using the below syntax. Syntax: $
wc filename

Department of BCA Page 23


Unix
Programming Vidyavahini First Grade College, Tumkur.

• If we want to display only lines in our file.


Syntax: $ wc -l filename
• If we want to display only words in our file.
Syntax: $ wc -w filename
• If we want to display only characters in our file.
Syntax: $ wc -c filename

split (split the content in our file)


By using this command we can split or share some information in one file to another file.

Sometimes larger files are impossible to store an editor at that time we can split up those files
automatically kernel created files like xaa, xab, xac….xaz etc.

These are the files kernel created files and these files we can store splitted data.

Syntax: split option filename

Ex: split -3 vvfgc

In the above example split command splits the 3 lines of information to store kernel files in vvfgc
file.

If we want to show that splitted content we use cat command

Syntax: cat kernelfile

Ex: cat xaa

More command(display 1 page at a time)

The more command is used to reads the file and display output one page at a time.

Syntax: more filename

Ex: more vvfgc

File Comparision Commands


cmp (comapare two files)

Department of BCA Page 24


Unix
Programming Vidyavahini First Grade College, Tumkur.

cmp command compares two files given as arguments byte by byte. The command does not display
any message, if the files are identical.

Syntax: cmp filename1 filename2

Ex: cmp file1 file2

comm (common contents in the files)


using this command we can store the common contents in both the files etc.

Syntax: comm option filename1 filename2

The comm command has without take any options it will display 3 column output.

• The first column contains unique lines to the first file.


• The second column contains unique lines to the second file.
The third column contains common content in both files.

Option purpose

-1 it hides or supress the output of


first file.

-2 it hides the second file output -3

it

hides the third column output.

diff (difference in 2 files)


It is used to which lines in one file have to be changed to make the two files identical.

diff uses specials and instructions to indicate the changes that are required to make two files identical.

Syntax: diff option filename1 filename2

Department of BCA Page 25


Unix
Programming Vidyavahini First Grade College, Tumkur.

Here action a is the add The

action d is the delete

The action c is the changes.

Ex: 4 d 5 it means delete the line 4 from first file and 5 th line in second file.

2 c 4 it means changes the line 2 in first line and 4th line in second file.

0 a 1,2 it means appending two lines after zero, they are added in the second file.

File Compression
Compression of data is when you take a regular size of a file and reduce the amount of disk space
it consumes. Then we need compression application.

gzip and gunzip commands: using these two commnds we can

compress and decompress the file.

When one file can zipped by using the gzip command we cannot open that file, at the time we use
gunzip command.

Syntax: gzip option filename

Syntax: gunzip option filename

Syntax: zcat filename

Using this commnad to view all compressed files.

Typical UNIX Directory Structure

The UNIX filesystem is laid out as a hierarchical tree structure which is anchored at a special top-level
directory known as the root (designated by a slash '/').
Because of the tree structure, a directory can have many child directories, but only one parent directory.

Department of BCA Page 26


Unix
Programming Vidyavahini First Grade College, Tumkur.

To specify a location in the directory hierarchy, we must specify a path through the tree.
The path to a location can be defined by an absolute path from the root /, or as a relative path
from the current working directory. To specify a path, each directory along the route from the
source to the destination must be included in the path, with each directory in the sequence being
separated by a slash. To help with the specification of relative paths, UNIX provides the
shorthand "." for the current directory and ".." for the parent directory. For example, the absolute
path to the directory "play" is /home/will/play, while the relative path to this directory from
"zeb" is ../will/play.

Directory Typical Contents

/ The "root" directory


/bin Essential low-level system utilities

/usr/bin Higher-level system utilities and application programs

/sbin Superuser system utilities (for performing system administration tasks)

Program libraries (collections of system calls that can be included in


/lib
programs by a compiler) for low-level system utilities

Department of BCA Page 27


Unix
Programming Vidyavahini First Grade College, Tumkur.

/usr/lib Program libraries for higher-level user programs

/tmp Temporary file storage space (can be used by any user)

/home or User home directories containing personal file space for each user. Each
/homes directory is named after the login of the user.

/etc UNIX system configuration and information files


/dev Hardware devices

A pseudo-filesystem which is used as an interface to the kernel. Includes a


/proc
sub-directory for each active program (or process).

Directory Commands

1. mkdir (make directory)

Syntax: $ mkdir directoryname

Using this commnad creates a subdirectory in the current working directory. You can only create
subdirectories in a directory if you have write permission on that directory.

We can create multiple directories at a time by using this commnad.

Syntax: $mkdir dir1 dir2 dir3 …. Dir n

2. cd (change [current working] directory)

Syntax: $ cd path

Using this command changes your current working directory to path (which can be an absolute or
a relative path). One of the most common relative paths to use is '..' (i.e. the parent directory of
the current directory).

Used without any target directory

Department of BCA Page 28


Unix
Programming Vidyavahini First Grade College, Tumkur.

$ cd dirname

resets your current working directory to your home directory (useful if you get lost). If you change
into a directory and you subsequently want to return to your original directory, use

$ cd -

3. pwd (print [current] working directory)

pwd displays the full absolute path to the your current location in the filesystem. So

Syntax: $ pwd

$ pwd
/usr/bin

implies that /usr/bin is the current working directory.


4. rmdir (remove directory)
using this commnand removes the subdirectory from the current working directory.
You can only remove subdirectories if they are completely empty (i.e. of all entries
besides the '.' and '..' directories).

Syntax: $ rmdir directoryname

5. mv (move/rename)

mv is used to rename files/directories and/or move them from one directory into another.
Exactly one source and one destination must be specified:

Syntax: $ mv source destination

If destination is an existing directory, the new name for source (whether it be a file or a directory)
will be destination/source. If source and destination are both files, source is renamed destination.
if destination is an existing file it will be destroyed and overwritten by source (you can use the -i
option if you would like to be asked for confirmation before a file is overwritten in this way).

Department of BCA Page 29


Unix
Programming Vidyavahini First Grade College, Tumkur.

Wild card Characters (or) Special Characters

A wildcard is a character that can be used as a substitute for any of a class of characters in a search,
there by greatly increasing the flexibility and efficiency of searches.

Wildcards are also used in regular expressions and programming languages. Regular expressions
are a pattern matching system that uses strings (i.e., sequences of characters) constructed according
to pre-defined syntax rules to find desired strings in text.

The wild card characters are * , ? , [ ] and { }.

In those first three characters are matching characters. { } this is expanding character.

1. Star (*) Wildcard:

It will display the all files and directories in current directory, if it is match.

Syntax: ls *

It will display the all directory files in a current directory.

Syntax: ls a*

It will display the all files in a current directory, whose files are starting with the letter “a”.

Syntax: ls *.sh

It will display the all files, whose extension will be .sh.

2. Question Mark (?) Wildcard:

The question mark (?) is used as a wildcard character in shell commands to represent
exactly one character, which can be any single character. Thus, two question marks in succession
would represent any two characters in succession, and three question marks in succession would
represent any string consisting of three characters.

Syntax: ls ?

It will display the all files in a current directory, whose files are having single character long.

Department of BCA Page 30


Unix
Programming Vidyavahini First Grade College, Tumkur.

Syntax: file???

It will display the all files in a current directory, whose files are having three character long.

Syntax: file a????

It will display the all files in a current directory, whose files are having five character long.

3. Square Brackets Wildcard:

The third type of wildcard in shell commands is a pair of square brackets, which can
represent any of the characters enclosed in the brackets.

Syntax: file *[xyz]*

Thus, for example, the following would provide information about all objects in the current directory
that have an x, y and/or z in them:

Syntax: ls *.[xyz]*

And the following would list all files that had an extension that begins with x, y or z:

Syntax: file [a-f]*


When a hyphen is used between two characters in the square brackets wildcard, it indicates a range
inclusive of those two characters. For example, the following would provide information about all
of the objects in the current directory that begin with any letter from a through f:

File System Layout


Every file has the following 4 types of blocks. They are as shown in below

Department of BCA Page 31


Unix
Programming Vidyavahini First Grade College, Tumkur.

Boot block:

This represents beginning program for each and every file system. This block contains a program
or software component is loader that is “bootstrap loader”.

Super block:

This is a special block in a file system. It contains

• The size of the file system.


• The length of the disk block.
• Updation of super block.
• Number of free nodes are available.

Inode block:

Each and every file has accessed by a unique number called inode number or inode entry or
inumber. (or)

Inodes are the data structures that contains information about files.

Functions of inode:

• Owner of a file.
• Group owner of a file.

Department of BCA Page 32


Unix
Programming Vidyavahini First Grade College, Tumkur.

• Types of the file.


• File accessing permissions
• Accessing time and modification time Number of links to that file. Size of that file.

Data block:

This contains all data and programs created by the users that is maintained by data block.

In this disk block size is 1024 bytes. If files contains only one character, an entire data block must
be maintained this single character only.

Accessing and storing files

Internally any file is identified in UNIX by a unique inode number. We can obtained that inode number
with including file names by using the “ ls –i “ option.

Syntax: ls -i filename

Ex: ls -i vvfgc Output: 12345 vvfgc

In the above example we display the inode number of perticular file “vvfgc”. Here 12345 is the inode
of vvfgc.

Inode number is nothing but an index into the inode table where the information about the files are
stored. Each inode entry in the inode table consists of 13 addresses.

Department of BCA Page 33


Unix
Programming Vidyavahini First Grade College, Tumkur.

In the above diagram 0 to 12 represent the addresses of the inode numbers. Each inode entry in the
data block must be having the 1KB data. The first 10 addresses (0 to 9) can store 10 KB of data. If
we give more than 10 KB of data then that structure divided into single indirection procedure to
store files.

When the file size is exceeding 266 blocks, the 12th entry comes into play. It points to double indirect
procedure.

The 13th and final entry of the address table points to a triple indirection procedure, when the file size
has exceeded 266 X 266 blocks.

Department of BCA Page 34


Unix
Programming Vidyavahini First Grade College, Tumkur.

Chapter-4

Special tools and Utilities (Filters) Definition:

Filters are the Unix commands which can access some data as input perform manipulation
on it and produces output.

They perform some filtering action on the data is known as filter.

Filter Commands

1. The grep Command:


The grep program searches a file or files for lines that have a certain pattern.

The syntax is: $grep pattern file(s)


The name "grep" derives from the ed (a UNIX line editor) command g/re/p which means "globally
search for a regular expression and print all lines containing it."

A regular expression is either some plain text (a word, for example) and/or special characters used
for pattern matching.

The simplest use of grep is to look for a pattern consisting of a single word. It can be used in a
pipe so that only those lines of the input files containing a given string are sent to the standard
output. If you don't give grep a filename to read, it reads its standard input; that's the way all filter
programs work:

$ ls -l | grep "Aug"
-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros

There are various options which you can use along with grep command:
Option Description
-v Print all lines that do not match pattern.
-n Print the matched line and its line number.
-l Print only the names of files with matching lines (letter "l") -
c Print only the count of matching lines.

Department of BCA Page 35


Unix
Programming Vidyavahini First Grade College, Tumkur.

-i Match either upper- or lowercase.

Next, let's use a regular expression that tells grep to find lines with "carol", followed by zero or
more other characters abbreviated in a regular expression as ".*"), then followed by "Aug". Here
we are using -i option to have case insensitive search:

$ ls -l | grep -i "carol.*aug"
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
2. The sort Command
The sort command arranges lines of text alphabetically or numerically. The example below sorts the
lines in the food file

$ sort food
Afghani Cuisine
Bangkok Wok
Big Apple Deli
Isle of Java
Mandalay
Sushi and Sashimi
Sweet Tooth

The sort command arranges lines of text alphabetically by default. There are many options that control
the sorting:

Option Description
-n Sort numerically (example: 10 will sort after 2), ignore blanks and tabs.
-r Reverse the order of sort.
-f Sort upper- and lowercase together.
+x Ignore first x fields when sorting.

More than two commands may be linked up into a pipe. Taking a previous pipe example using grep,
we can further sort the files modified in August by order of size.

The following pipe consists of the commands ls, grep, and sort:

$ls -l | grep "Aug" | sort +4n


-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro

Department of BCA Page 36


Unix
Programming Vidyavahini First Grade College, Tumkur.

-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07


-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02

This pipe sorts all files in your directory modified in August by order of size, and prints them to
the terminal screen. The sort option +4n skip four fields (fields are separated by blanks) then
sorts the lines in numeric order.

2. The pg and more Commands

A long output would normally zip by you on the screen, but if you run text through more or pg as a
filter, the display stops after each screenful of text.

Let's assume that you have a long directory listing. To make it easier to read the sorted listing, pipe
the output through more as follows:

$ls -l | grep "Aug" | sort +4n | more


-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07 -rw-rw-r--
1 john doc 14827 Aug 9 12:40 ch03
.
..
-rw-rw-rw- 1 john doc 16867 Aug 6 15:56 ch05
--More--(74%)

The screen will fill up with one screenful of text consisting of lines sorted by order of file size. At
the bottom of the

screen is the more prompt where you can type a command to move through the sorted text.

When you're done with this screen, you can use any of the commands listed in the discussion of the
more program.

3. Head command
head outputs the first part of files
Syntax: head [options] filename Selected
options:
– -cn : print the first n characters of the file

Department of BCA Page 37


Unix
Programming Vidyavahini First Grade College, Tumkur.

– -n : print the first n lines the default is 10

head –c5 abc # displays first 5 characters (includes whitespace)


head abc # displays first 10 lines of abc ls | head -15 # displays
first 15 lines of file listing

4. Tail command
tail outputs the last part of files Format:
tail [options] filename
• Selected options:
– -cn : print the last n characters of the file
– -n : print the last n lines the default is 10

• Command:
tail –c5 abc # displays last 5 characters (includes whitespace) tail
abc # displays last 10 lines of abc
• Pipe
ls | tail -15 # displays last 15 lines of file listing head
abc | tail -5 # prints lines 6 through 10 of file abc

5. Uniq Command
Format: uniq [options] filename

uniq removes duplicate adjacent lines from a file


• To ensure that all of the data is unique you should sort the file first (recall that sort also can
produce unique values with the –u option)
• Options (selected):
– -c : count the instances
– -d : print only the duplicates (once)
– -u : print only the unique lines
– -n : ignore first n fields
• Command:
uniq –u abc # only prints out the unique lines in file abc assuming duplicates are next to each other
(without the –u, uniq will print out all of the lines, but only once, the 2nd or more duplicate lines
will not print out)
uniq –c abc # only prints out the count of unique lines assuming duplicates are next to each other
• Pipe:

Department of BCA Page 38


Unix
Programming Vidyavahini First Grade College, Tumkur.

sort abc | uniq –c # put abc in order and tell me how many lines are unique

6. Cut command

cut removes columns or fields from a line

Format: cut [options] filename Options:


*lists may be specified using integers separated by commas, ranges are separated by
hyphens (-) Examples: 1,5-7 means units 1,5,6,7 and 1,5- means units 1,5 and beyond to
end of line

Examples:

cut -d: -f5 /etc/passwd (print only the 5th field, delimited by colon(:), of the /etc/passwd file) cut

–d” “ –f2 shuffled (print only the 2nd field, delimited by a space, from file shuffled)

cut –c4-8 shuffled (print only the columns 4 through 8 of each line in shuffled.

Example: ls | wc –l

This particular command:


1. gets a list of the files in the directory

Department of BCA Page 39


Unix
Programming Vidyavahini First Grade College, Tumkur.

2. sends this list through the pipe


3. the filter counts the lines of the data received
The result is equivalent to: The number of files in the directory

Department of BCA Page 40


Unix
Programming Vidyavahini First Grade College, Tumkur.

Department of BCA Page 41


Unix
Programming Vidyavahini First Grade College, Tumkur.

Department of BCA Page 42


Unix
Programming Vidyavahini First Grade College, Tumkur.

Chapter-5 Process
Management

Process:

Program which is in execution is nothing but a process. It is an active entity.

There are 2 main states of the process. They are

• Born state Die state

When the process starts execution that state is known as born state. In this state program is alive.

After completion of execution that process is said to be in die state.

Every process has 2 types of attributes. They are

• Process id (pid)
• Parent process id (ppid)

Process id:

Each process has uniquely identified by a number is called process id. In shortcut we
represents it as “pid”. It has taking integer values only and its range will be 0 to 30000.

The kernel will assign pid when a new process is created. We can obtain that process id
by using “getpid()” system call.

Syntax: int getpid ( );

Processed process staes

0 born state of the process 1 start of the


process
2 execution of the process

Parent process id:

every process has a parent process and it should have one id that is “ppid”. It will be
obtained by using the syntax int getppid ( ); it will also takes only integer values.

Department of BCA Page 43


Unix
Programming Vidyavahini First Grade College, Tumkur.

Shell process
When we login to the Unix system a process is immediately setup by the kernel and shell will be
activated. To know the pid of our current shell by using the following syntax.

Syntax: $echo $$

Output: 291

Here 291 is the process id of currently running shell.

We can obtain currently running shell by using the following syntax.

Syntax: $echo $SHELL

Output: bin/bash

Process state Transition


The life time of a process can be divided into different types of states. They are

• new state
• ready state
• running state
• sleeping state
• terminated (or) zombie state

Department of BCA Page 44


Unix
Programming Vidyavahini First Grade College, Tumkur.

New state:

in this state process is created through the fork( ) system call. The fork( ) system call creates
the child processes those are identical to the parent process.

Syntax: $ fork ( )

Ready state:

In this state process is not running, but it is ready for run as soon as the kernel schedules the
process.

Running state:

In this Unix OS 2 types of running states. They are

• kernel running user running

one process is executed through the exec ( ) system call we can mention the process name and
arguments.

Syntax: $ exec * (“process name” [ args ] );

Department of BCA Page 45


Unix
Programming Vidyavahini First Grade College, Tumkur.

Here * is nothing but meta character. It will show the all information about that process. And arguments
are array of characters.

Sleeping state:

In this state process is in sleeping mode at the time it cannot continued execution because
of some resources are unavailability. It can be obtained by sleep ( ) system call. Syntax: $ sleep
();

Zombie state:

After completion of execution the process will be exit or terminated through the exit ( ) system
call. This is the final state of the process.

Syntax: $ exit ( ) ;

What is spawning?

When one process creates another new process is known as spawning. Here existing process is
called as parent process and newly created process is child process.

Process related commands

Ps (process status) command

It is easy to see your own processes by running the ps (process status) command as follows:

Syntax: $ ps option

$ ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh
18361 ttyp3 00:01:31 abiword
18789 ttyp3 00:00:00 ps

One of the most commonly used flags for ps is the -f ( f for full) option, which provides more
information as shown in the following example:

$ ps -f

Department of BCA Page 46


Unix
Programming Vidyavahini First Grade College, Tumkur.

UID PID PPID C STIME TTY TIME CMD


amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh amrood
6892 3662 4 10:51:50 pts/6 0:00 ps -f Here is the
description of all the fileds displayed by ps -f command:

Column Description
UID User ID that this process belongs to (the person running it).
PID Process ID.
PPID Parent process ID (the ID of the process that started it).
C CPU utilization of process.
STIME Process start time.
TTY Terminal type associated with the process
TIME CPU time taken by the process.
CMD The command that started this process.
There are other options which can be used along with ps command:

Option Description
-a Shows information about all users
-x Shows information about processes without terminals.
-u Shows additional information like -f option.
-e Display extended information.
Stopping Processes(kill command)

Ending a process can be done in several different ways. Often, from a console-based command,
sending a CTRL + C keystroke (the default interrupt character) will exit the command. This works
when process is running in foreground mode.

If a process is running in background mode then first you would need to get its Job ID using ps
command and after that you can use kill command to kill the process as follows:

$ps -f
UID PID PPID C STIME TTY TIME CMD
amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh amrood
6892 3662 4 10:51:50 pts/6 0:00 ps -f

Department of BCA Page 47


Unix
Programming Vidyavahini First Grade College, Tumkur.

$kill 6738
Terminated

Here kill command would terminate first_one process. If a process ignores a regular kill command,
you can use kill -9 followed by the process ID as follows:

$kill -9 6738
Terminated

Starting a Process

When you start a process (run a command), there are two ways you can run it:

• Foreground Processes
• Background Processes

Foreground Processes:

By default, every process that you start runs in the foreground. It gets its input from the keyboard and
sends its output to the screen.

You can see this happen with the ls command. If I want to list all the files in my current directory,
I can use the following command:

$ls ch*.doc

This would display all the files whose name start with ch and ends with .doc:

ch01-1.doc ch010.doc ch02.doc ch03-2.doc ch04-1.doc


ch040.doc ch05.doc ch06-2.doc ch01-2.doc ch02-1.doc

The process runs in the foreground, the output is directed to my screen, and if the ls command wants
any input (which it does not), it waits for it from the keyboard.

While a program is running in foreground and taking much time, we cannot run any other
commands (start any other processes) because prompt would not be available until program finishes
its processing and comes out.

Background Processes:

Department of BCA Page 48


Unix
Programming Vidyavahini First Grade College, Tumkur.

A background process runs without being connected to your keyboard. If the background process
requires any keyboard input, it waits.

The advantage of running a process in the background is that you can run other commands; you do
not have to wait until it completes to start another!

The simplest way to start a background process is to add an ampersand ( &) at the end of the command.

$ls ch*.doc &

This would also display all the files whose name start with ch and ends with .doc:

ch01-1.doc ch010.doc ch02.doc ch03-2.doc ch04-


1.doc ch040.doc ch05.doc ch06-2.doc ch01-2.doc
ch02-1.doc

Here if the ls command wants any input (which it does not), it goes into a stop state until I move it
into the foreground and give it the data from the keyboard.

That first line contains information about the background process - the job number and process ID.
You need to know the job number to manipulate it between background and foreground.

If you press the Enter key now, you see the following:

[1] + Done ls ch*.doc &


$

The first line tells you that the ls command background process finishes successfully. The second is
a prompt for another command.

Daemon Processes:

Daemons are system-related background processes that often run with the permissions of root and
services requests from other processes.
A daemon process has no controlling terminal. It cannot open /dev/tty. If you do a "ps -ef" and look
at the tty field, all daemons will have a? for the tty.

More clearly, a daemon is just a process that runs in the background, usually waiting for something
to happen that it is capable of working with, like a printer daemon is waiting for print commands.

If you have a program which needs to do long processing then it’s worth to make it a daemon and
run it in background.

Department of BCA Page 49


Unix
Programming Vidyavahini First Grade College, Tumkur.

The top Command


The top command is a very useful tool for quickly showing processes sorted by various criteria.

It is an interactive diagnostic tool that updates frequently and shows information about physical and
virtual memory, CPU usage, load averages, and your busy processes.

Here is simple syntax to run top command and to see the statistics of CPU utilization by different
processes: $top

Process scheduling commands

The at command

The at command executes commands at a given time, using your default shell unless you tell the
command otherwise (see the man page).

The options to at are rather user-friendly, which is demonstrated in the examples below:

steven@home:~> at tomorrow + 2 days warning: commands will be


executed using (in order) a) $SHELL
b) login shell c) /bin/sh at>
cat reports | mail myboss@mycompany at>
<EOT>
job 1 at 2001-06-16 12:36
Typing Ctrl+D quits the at utility and generates the "EOT" message.

The -m option sends mail to the user when the job is done, or explains when a job can't be done.
The command at q lists jobs; perform this command before submitting jobs in order prevent them
from starting at the same time as others. With the atrm command you can remove scheduled jobs
if you change your mind.

For example, jobs are often run at exactly 1 o'clock in the morning (e.g. system indexing to update
a standard locate database), so entering a time of 0100 may easily slow your system down rather
than fire it up. To prevent jobs from running all at the same time, you may also use the batch
command, which queues processes and feeds the work in the queue to the system in an evenly
balanced way, preventing excessive bursts of system resource usage. See the Info pages for more
information.

Cron and crontab

Department of BCA Page 50


Unix
Programming Vidyavahini First Grade College, Tumkur.

The cron system is managed by the cron daemon. It gets information about which programs and
when they should run from the system's and users' crontab entries. Only the root user has access to
the system crontabs, while each user should only have access to his own crontabs. On some
systems (some) users may not have access to the cron facility.

At system startup the cron daemon searches /var/spool/cron/ for crontab entries which are
named after accounts in /etc/passwd, it searches /etc/cron.d/ and it searches /etc/crontab,
then uses this information every minute to check if there is something to be done. It executes
commands as the user who owns the crontab file and mails any output of commands to the owner.

Alternative

You could also use the crontab -l command to display crontabs.

Some variables are set, and after that there's the actual scheduling, one line per job, starting with 5
time and date fields. The first field contains the minutes (from 0 to 59), the second defines the
hour of execution (0-23), the third is day of the month (1-31), then the number of the month (112),
the last is day of the week (0-7, both 0 and 7 are Sunday). An asterisk in these fields represents
the total acceptable range for the field. Lists are allowed; to execute a job from Monday to Friday
enter 1-5 in the last field, to execute a job on Monday, Wednesday and Friday enter 1,3,5.

Chapter-6

Shell Programming
The shell provides you with an interface to the UNIX system. It gathers input from you and executes
programs based on that input. When a program finishes executing, it displays that program's output.

Department of BCA Page 51


Unix
Programming Vidyavahini First Grade College, Tumkur.

A shell is an environment in which we can run our commands, programs, and shell scripts. There
are different flavors of shells, just as there are different flavors of operating systems. Each flavor
of shell has its own set of recognized commands and functions.

Shell Prompt:
The prompt, which is called command prompt, is issued by the shell. While the prompt is displayed, you
can type a command.

The shell reads your input after you press Enter. It determines the command you want executed by
looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs
separate words.

Following is a simple example of date command which displays current date and time:

$date

Thu Jun 25 08:30:19 MST 2009

Shell Types:

In UNIX there are two major types of shells:

1. The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $
character.
2. The C shell. If you are using a C-type shell, the default prompt is the % character.

There are again various subcategories for Bourne Shell which are listed as follows:

• Bourne shell ( sh)


• Korn shell ( ksh)
• Bourne Again shell ( bash)
• POSIX shell ( sh)
The different C-type shells follow:

• C shell ( csh)

Department of BCA Page 52


Unix
Programming Vidyavahini First Grade College, Tumkur.

• TENEX/TOPS C shell ( tcsh)

The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he was at AT&T
Bell Labs in New Jersey.

The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as "the shell".

The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this reason, it is the
shell of choice for writing scripts to use on several different versions of UNIX.

Shell Scripts:

The basic concept of a shell script is a list of commands, which are listed in the order of execution.
A good shell script will have comments, preceded by a pound sign, #, describing the steps.

There are conditional tests, such as value A is greater than value B, loops allowing us to go
through massive amounts of data, files to read and store data, and variables to read and store
data, and the script may include functions.

Shell scripts and functions are both interpreted. This means they are not compiled.

It supports less features. It supports input and output redirection operators.

Example Script:

Assume we create a test.sh script. Note all the scripts would have .sh extension. Before you add
anything else to your script, you need to alert the system that a shell script is being started. This is
done using the shebang construct. For example:

#!/bin/sh

This tells the system that the commands that follow are to be executed by the Bourne shell. It's called
a shebang because the # symbol is called a hash, and the ! symbol is called a bang.

To create a script containing these commands, you put the shebang line first and then add the commands:
#!/bin/bash
pwd
ls

Department of BCA Page 53


Unix
Programming Vidyavahini First Grade College, Tumkur.

Shell Comments:

You can put your comments in your script as follows:

#!/bin/bash

# this is vvfgc
# Copyright (c) vvfgc.com
# Script follows here: pwd
ls

Now you save the above content and make this script executable as follows:

$chmod +x test.sh

Now you have your shell script ready to be executed as follows: $./test.sh

Extended Shell Scripts:

The shell is, after all, a real programming language, complete with variables, control structures, and
so forth. No matter how complicated a script gets, however, it is still just a list of commands
executed sequentially.

Following script use the read command which takes the input from the keyboard and assigns it as
the value of the variable PERSON and finally prints it on STDOUT.

echo "What is your name?"


read PERSON echo "Hello,
$PERSON"

Here is sample run of the script:

$./test.sh
What is your name? vvfgc
Hello, vvfgc
Variables

Department of BCA Page 54


Unix
Programming Vidyavahini First Grade College, Tumkur.

Variable is value that always changes during execution of a program. It is an integral part of shell
programming. They provide the ability to store and manipulate information.

There are 2 types of variables. They are

• Environment variables
• User defined variables

Environment variables:

These variables are the part of the system and these are created and maintained by the
syatem itself. These variables always in capital letters only.

Variable meaning

PS1 this is first prompt setting in Unix ($)

PS2 this is second prompt setting in Unix (>)

PATH whether we are used absolute or relative path.

HOME it stores the current root directory.

LOGNAME it stores the login name of the user.


User defined variable:

Variables are defined as follows::

variable_name = variable_value

For example:

NAME = "vvfgc"

Above example defines the variable NAME and assigns it the value "vvfgc". Variables of this type
are called scalar variables. A scalar variable can hold only one value at a time.

The shell enables you to store any value you want in a variable. For example:
VAR1="vvfgc " VAR2=100

Department of BCA Page 55


Unix
Programming Vidyavahini First Grade College, Tumkur.

Accessing Values to variables:

To access the value stored in a variable, prefix its name with the dollar sign ( $):

For example, following script would access the value of defined variable NAME and would print it
on STDOUT:

NAME="vvfgc " echo


$NAME

This would produce following value:

Output: vvfgc

Read-only Variables:

The shell provides a way to mark variables as read-only by using the “read only” command. After
a variable is marked read-only, its value cannot be changed.

For example, following script would give error while trying to change the value of NAME:

NAME="vvfgc " readonly


NAME
NAME="Qadiri"

This would produce following result:

/bin/sh: NAME: This variable is read only.

Unsetting Variables:

Unsetting or deleting a variable tells the shell to remove the variable from the list of variables that
it tracks. Once you unset a variable, you would not be able to access stored value in the variable.

Following is the syntax to unset a defined variable using the unset command: unset

variable_name

Above command would unset the value of a defined variable. Here is a simple example

NAME="vvfgc" unset
NAME echo $NAME

Department of BCA Page 56


Unix
Programming Vidyavahini First Grade College, Tumkur.

Above example would not print anything. You cannot use the unset command to unset variables that
are marked readonly.

Read command

This command is used to take the input from the user.

Syntax: $read var1 var2 var3 ….. var n

Syntax: $ read var1

The variable used along with the read command need not be preceded by the $ symbol.

Ex: clear echo “enter ur name” read name echo “hello $name”

Output: enter ur name :vvfgc

Hello vvfgc

Expr command

This command is used to perform mathematical caluculations.

Syntax: ` expr operand1 operator operand2 `

Where ( ` ) this symbol is known as grep symbol. There is always must a space between symbol

and the expr command. Ex: clear echo “enter 2 numbers” read a b

echo “ sum of 2 numbers is ` expr $a + $b ` “


echo “ sub of 2 numbers is ` expr $a - $b ` “ echo

“ product of 2 numbers is ` expr $a \* $b ` “ echo “

quotient of 2 numbers is ` expr $a / $b ` “ Note:

In unix multiplication purpose we use the symbol of “\*” because only * is wild card character.

Department of BCA Page 57


Unix
Programming Vidyavahini First Grade College, Tumkur.

Test operator [numerical test] Arithmetic

Operators:

There are following arithmetic operators supported by Bourne Shell.

Assume variable “a” holds 10 and variable “b” holds 20 then:

Show Examples

Operator Description Example


Addition - Adds values on either side of the
+ `expr $a + $b` will give 30
operator
Subtraction - Subtracts right hand operand from
- `expr $a - $b` will give -10
left hand operand
Multiplication - Multiplies values on either side
* `expr $a \* $b` will give
200 of the operator
Division - Divides left hand operand by right
/ `expr $b / $a` will give 2
hand operand
Modulus - Divides left hand operand by right
% `expr $b % $a` will give 0
hand operand and returns remainder
Assignment - Assign right operand in left a=$b would assign value of b into a
=
operand
Equality - Compares two numbers, if both are [ $a == $b ] would
==
return same then returns true. false.
Not Equality - Compares two numbers, if both [ $a != $b ] would return
!=
are different then returns true. true.
It is very important to note here that all the conditional expressions would be put inside square braces
with one spaces around them, for example [ $a == $b ] is correct where as [$a==$b] is incorrect.

All the arithmetical calculations are done using long integers.


Relational Operators:

Department of BCA Page 58


Unix
Programming Vidyavahini First Grade College, Tumkur.

Bourne Shell supports following relational operators which are specific to numeric values. These
operators would not work for string values unless their value is numeric.

For example, following operators would work to check a relation between 10 and 20 as well as in
between "10" and "20" but not in between "ten" and "twenty".

Assume variable “a” holds 10 and variable “b” holds 20 then:

Show Examples

Operator Description Example


Checks if the value of two operands is equal or
-eq [ $a -eq $b ] is not true.
not, if yes then condition becomes true.
Checks if the value of two operands is equal or
-ne not, if values are not equal then condition [ $a -ne $b ] is true.
becomes true.
Checks if the value of left operand is greater
-gt than the value of right operand, if yes then [ $a -gt $b ] is not true.
condition becomes true.
Checks if the value of left operand is less than
-lt the value of right operand, if yes then condition [ $a -lt $b ] is true. becomes
true.
Checks if the value of left operand is greater
-ge than or equal to the value of right operand, if [ $a -ge $b ] is not true.
yes then condition becomes true.
Checks if the value of left operand is less than
-le or equal to the value of right operand, if yes [ $a -le $b ] is true.
then condition becomes true.

It is very important to note here that all the conditional expressions would be put inside square braces
with one spaces around them, for example [ $a <= $b ] is correct where as [$a <= $b] is incorrect.

Boolean Operators (or) logical operators:

There are following Boolean operators supported by Bourne Shell.

Department of BCA Page 59


Unix
Programming Vidyavahini First Grade College, Tumkur.

Assume variable “a” holds 10 and variable “b” holds 20 then:


Show Examples

Operator Description Example


This is logical negation. This inverts a true
! [ ! false ] is true.
condition into false and vice versa.
This is logical OR. If one of the operands is [ $a -lt 20 -o $b -gt 100 ] is
-o
true then condition would be true. true.
This is logical AND. If both the operands are
[ $a -lt 20 -a $b -gt 100 ] is
-a true then condition would be true otherwise it
false. would
be false.

String test Operators


There are following string operators supported by Bourne Shell.

Assume variable a holds "abc" and variable b holds "efg" then:

Show Examples

Operator Description Example


Checks if the value of two operands is equal or
= [ $a = $b ] is not true.
not, if yes then condition becomes true.
Checks if the value of two operands is equal or
!= not, if values are not equal then condition [ $a != $b ] is true.
becomes true.
Checks if the given string operand size is zero.
-z [ -z $a ] is not true.
If it is zero length then it returns true.
Checks if the given string operand size is non-
-n [ -n $a ] is true.
zero. If it is non-zero length then it returns true. Check if str is not the empty
string. If it is str [ $a ] is not false.
empty then it returns false.

Department of BCA Page 60


Unix
Programming Vidyavahini First Grade College, Tumkur.

File Test Operators


There are following operators to test various properties associated with a Unix file.

Assume a variable file holds an existing file name "test" whose size is 100 bytes and has read, write
and execute permission on:

Show Examples
Operator Description Example
Checks if file is a block special file if yes then
-b file [ -b $file ] is false.
condition becomes true.
Checks if file is a character special file if yes
-c file [ -b $file ] is false.
then condition becomes true.
Check if file is a directory if yes then condition
-d file [ -d $file ] is not true.
becomes true.
Check if file is an ordinary file as opposed to a
-f file directory or special file if yes then condition [ -f $file ] is true. becomes true.
Checks if file has its set group ID (SGID) bit
-g file [ -g $file ] is false.
set if yes then condition becomes true.
Checks if file has its sticky bit set if yes then
-k file [ -k $file ] is false.
condition becomes true.
Checks if file is a named pipe if yes then
-p file [ -p $file ] is false.
condition becomes true.
Checks if file descriptor is open and associated
-t file with a terminal if yes then condition becomes [ -t $file ] is false.
true.
Checks if file has its set user id (SUID) bit set
-u file [ -u $file ] is false.
if yes then condition becomes true.
Checks if file is readable if yes then condition
-r file [ -r $file ] is true.
becomes true.

Department of BCA Page 61


Unix
Programming Vidyavahini First Grade College, Tumkur.

Check if file is writable if yes then condition


-w file [ -w $file ] is true.
becomes true.
Check if file is execute if yes then condition
-x file [ -x $file ] is true.
becomes true.
Check if file has size greater than 0 if yes then
-s file [ -s $file ] is true.
condition becomes true.
Check if file exists. Is true even if file is a
-e file [ -e $file ] is true.
directory but exists.

Control statements
The ability to control the flow of execution of program is known as control statements.

The different types of control structures are

• Sequence control structure


• Selection control structure
• Looping control structure
Selection control structure
This type of instruction allows the shell script to be executed depending on the condition.

There are mainly 4 types of decision making instructions. They are

• if-then-fi statement
• if-then-else-fi statement
• if-then-elif-then-else-fi statement case-esac statement if-then-fi statement:

in this first check the condition. That condition is true then only the if block statements will
be executed otherwise the cursor transfer outside the if condition.

Syntax: ex:

Department of BCA Page 62


Unix
Programming Vidyavahini First Grade College, Tumkur.

if [ condition ] if [ $a –gt 18 ]

then then

statements echo “eligible for vote”

fi fi

if-then-else-fi statement:

in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the else block statements will be executed.

Syntax: ex:

if [ condition ] if [ $a –gt $b ]

then then

statements echo “a is larger than b” else

else

statements echo “b is larger than a”

fi fi

if-then-elif-then-else-fi statement:

in this first check the condition. That condition is true then only the if block statements
will be executed otherwise the cursor checks the next condition then the second condition will be
true then inside that statements will be executed and so on. If any conditions were not true then the
else block statements will be executed.

Syntax: ex:

if [ condition 1 ] if [ $a –gt $b –a $a –gt $c ]

then then

Department of BCA Page 63


Unix
Programming Vidyavahini First Grade College, Tumkur.

statements echo ”a is larger”

elif [ condition 2] elif [ $b –gt $c ]

then then

statements echo “ b is larger”

else else

statements echo “c is larger”

fi fi

Case-esac statement:

Syntax: case $variable in

[match1] ) statements ; ;

[match2] statements ; ;

[match3] statements ; ;

: :

: :

*) statements ; ;

esac

• here match1,match2 etc are the case labels.


• When a case statement is evaluated the value of variable is matched in any one of the choices.
• When a match is found then shell executes that corresponding match statements.
• The pair of semicolon at the end of every choices. It identifies break.
• *) indicates default class. Ex: clear echo “enter a character”

read ch

case $ch in

Department of BCA Page 64


Unix
Programming Vidyavahini First Grade College, Tumkur.

[a-z]) echo “entered character is lowercase letters” ; ;

[A-Z] echo “entered character is uppercase letters” ; ;

[0-9] echo “entered character isdigit” ; ;

*) echo “invalid choice” ;;

esac

Looping Control statements


In this all statements are executed repeatedly again and again as long as condition is true. This is also
known as repetition or iteration.

Shell allows various types of looping. They are

• While loop
• Until loop
• For loop

While loop:

This is the pretested loop or entry controlled loop. In this first check the condition, if that
condition was true then control enter inside the loop otherwise control transferred outside the loop.

Syntax: ex:

while [ condition ] while [ i –le 10 ]

do do

Statements echo “$i”


done i =` expr $i + 1 `

done

until loop:

This is also pretested loop or entry controlled loop. In this first check the condition, if that
condition was false then control enter inside the loop otherwise control transferred outside the loop.

Syntax: ex:

Department of BCA Page 65


Unix
Programming Vidyavahini First Grade College, Tumkur.

until [ condition ] until [ i -ge 10 ]

do do

Statements echo “$i” done

i =` expr $i + 1 `

done

for loop:

This is a fixed execution loop. This loop is allow to execute list of statements certain period of
time.

Syntax:

for variable in value1 value2 value3 ….. value n

do

statements

done

ex: for i in 1 2 3

45

do

echo $i

i=` expr $i + 1 ` done

Sample programs

1. # script to find even number series up to given limit.

Department of BCA Page 66


Unix
Programming Vidyavahini First Grade College, Tumkur.

clear

even=0 echo “enter the

limit” read limit while [

$even –le $limit ] do

echo “$even” even=`

expr $even + 2 `

done

2. # script to find odd number series up to given limit.


clear

odd=1

echo “enter the limit”

read limit while [ $odd –

le $limit ] do

echo “$odd”

odd=` expr $odd + 2 `

done

3. # script to generate the series 1,3,2,4,3,5,4,6,5……..


clear

a=1 b=3

while [

$a –le

Department of BCA Page 67


Unix
Programming Vidyavahini First Grade College, Tumkur.

10 ] do

echo

“$a,\c”

echo

‘$b,\c”

a=`

expr $a

+1`

b=`

expr $b

+1`

done

4. # script for multiplication table.


clear echo “enter a
number” read n i=1
while [ $i –le 10 ] do

p=` expr $n \* $i `
echo “$n * $i = $p” i=`
expr $i + 1 ` done

5. #script to check whether the given number is even number or not.

Department of BCA Page 68


Unix
Programming Vidyavahini First Grade College, Tumkur.

clear echo “enter a


number” read n

if [ ` expr $n % 2 ` -eq 0 ] then

echo “$n is an even number”


else

echo “$n is an odd number”


fi

6. #script to find factorial of a given number


clear echo “enter a
number” read n if [ $n
–ge 0 ] then

i=1
f=1
while [ $i –le $n ]
do
f=` expr $f \* $i `
i=` expr $i + 1 `
done
echo “factorial of $n is $f”

else
echo “enter a positive number”

fi
7. #script to check whether the given year is leap year or not.

Department of BCA Page 69


Unix
Programming Vidyavahini First Grade College, Tumkur.

clear echo “enter a


year” read year

if [ ` expr $year % 4 ` -eq 0 ] then


echo “$year is a leap year” else

echo “$year is not leap year”

fi

8. # script to print reverse of a given string.


clear echo “enter a
string” read str l=`
expr length $str `
while [ $l –ge 1 ] do

c=` echo $str | cut –c $l `


strrev=$strrev$c l=` expr
$l – 1 ` done echo “original
string is $str” echo “reverse
string is $strrev”

9. #script to find the number of vowels in a string clear echo “enter a


string” read str count=0 l=` expr length $str ` i=1 while [ $i –le $l ] do

ch=` echo $str | cut –c $i `


case $ch in [aeiouAEIOU])
count=` expr $count + 1 ` ;;

Department of BCA Page 70


Unix
Programming Vidyavahini First Grade College, Tumkur.

esac

i=` expr $i + 1 `
done echo “string is
$str”

echo “number of vowels in the string $count”

10.# This script displays the date, time, username and current
directory.

echo "Date and time is:"


date echo echo "Your username is:
`whoami` \n"
echo "Your current directory is: \c" pwd

11.#!/bin/bash
x=10 #NOT x = 10 no spaces X=20
#variables are case sensitive
$y= #NULL variable
echo "x = $x" echo
"X = $X" echo "y
= $y"

12.Script to write swap 2 numbers


clear echo ‘enter 2
numbers” read a b
temp=$a a=$b b=$temp
echo “after swapping”
echo “the value of a is $a”
echo “the value of b is $b”

Chapter-7

Department of BCA Page 71


Unix
Programming Vidyavahini First Grade College, Tumkur.

Unix System Communication

Communication is an excellent feature of communicating one user with another user.

The users can easily send mails, data, images, pictures etc information to the another users through
the server. Sometimes there are thousands of users sharing the system resources. At that time these
communication commands can be used.

Those commands are

• Write command
• Wall command
• Mesg command
• Finger command
• Mail command
• News command Write command:

Using this command we can send a message to another one user only. If the recipient has take the
permission to receive the messages. Otherwise he cannot receive any messages from other users.

Syntax

$ write person [ttyname]

If you wish to talk to someone on your own machine, then person is just the person's Person
login name. If you wish to talk to a user on another host, then person is of the form 'user@host'.
If you wish to talk to a user who is logged in more than once, the ttyname argument may
ttyname be used to indicate the appropriate terminal name, where ttyname is of the form 'ttyXX' or
'pts/X'.

Examples

Write vvfgc

Typing the above command would start a talking session with the vvfgc . If you type your name, you
can echo back
If we are return back our prompt press ctrl+d

Department of BCA Page 72


Unix
Programming Vidyavahini First Grade College, Tumkur.

Again we are transferred to another user the we press ctrl+alt+f1 so on

Mesg command:

This command shows users either interact to receive the messages or not.

Here also recipient must be login otherwise error message will be displayed.

Lets you control if people can use the write command, to send text to you over the screen.

Syntax

$ mesg [n | y]

n  Prevents the messages from others popping up on your screen. Y


 Allows messages to appear on your screen.

Examples
mesg
Typing this command by itself will display whether or not the mesg service is enabled. For example,
it may display: "is y", indicating that it is enabled. Typing n or why after the command would
enable or disable this command.

When this command is disabled non-root users will be unable to to send messages to you using message
commands such as talk or write.

Wall command:
Wall sends a message to everybody logged in with their mesg permission set to yes. The
message can be given as an argument to wall, or it can be sent to wall's standard input. When
using the standard input from a terminal, the message should be terminated with the EOF key
(usually Control-D).

Syntax

$ wall [-n] [-t TIMEOUT] [file]

wall displays the contents of file or, by default, its standard input, on the terminals of all currently
logged in users. The command will cut over 79 character long lines to new lines. Short lines are
white space padded to have 79 characters. The command will always put carriage return and new
line at the end of each line.

Department of BCA Page 73


Unix
Programming Vidyavahini First Grade College, Tumkur.

Only the super user can write on the terminals of users who have chosen to deny messages or are using
a program which automatically denies messages.

Reading from a file is refused when the invoker is not super user and the program is sued or said.

Examples

Wall there is hope

Typing the above command from root would broadcast "there is hope" to all other users termial
who are logged into the computer. Below is an example of what each terminal would show after the
wall post.

Broadcast message from root (pts/1) (Thu May 23 08:28:21 2013):

there is hope

Echo AWESOME | wall

Sends the message "AWESOME" to all users.

Finger command:

This command displays the information about the system users, who are presently loged
in.

Syntax: $finger

-l option: it will display the detail information about the users.

Here * symbol indicates that particular user have set the permission mesg n

Mail command:

Using this command we can send a mesg to all users who are presently login or not.

It can be used to quickly circulate memos and other information.

It can also be used to send messages to other users who have not currently logged in. Syntax:

$mail or $mail usernames

Department of BCA Page 74


Unix
Programming Vidyavahini First Grade College, Tumkur.

Department of BCA Page 75

Potrebbero piacerti anche