66
Key to Unix Page 1 of 63 www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414 1. Introduction to UNIX 1.1. Single-User Systems The personal computer (PC) is a small, general-purpose system that can execute programs to perform a wide variety of tasks. The PC, however, was designed for use by one person at a time; that is, it is Single- User oriented with MS-DOS as the de facto standard operating system for this range of machines. Single user systems became very popular due to the low cost hardware and wide range of software available for these machines. 1.2. Multi-user Systems As opposed to single-user systems there are also larger systems, which more than one person can use at any time. Such systems are referred to as multi-user systems. Multi-user systems would be required when a number of applications have to be run simultaneously, or common resources, like printers and disks, are to be shared by a number of users. 1.3. Hardware - Multi-user Systems. While the hardware components of a multi-user system are similar to that of a single-user system, the following differences should be noted: The CPU of a multi-user system is more powerful and has capabilities to support multi-programming and multi-tasking, two features essential for multi-user systems. The hard disk of a multi-user system is bigger in capacity. Most multi-user systems use magnetic tape as external storage for backup of software. Single-user systems use floppies as the backup device. This is because multi-user systems have large hard disks, which have to be backed up quickly and conveniently. Each user communicates with the system through a keyboard and a VDU - these are together referred to as the user terminal or node. A terminal may also be a PC or PC-XT. The terminal is connected to the system unit by cables through RS232 ports. The number of terminals varies between systems. In multi-user systems, there is one terminal designated as the console. The console consists of a Keyboard and VDU connected to the CPU directly through cables. From the console, the operation of the system is controlled. When power is switched on for the system unit, messages regarding the boot procedure appear on the console only. After the boot procedure is over, all the users can start working at their terminals. The console is also used to send messages to the users of the system and for other operations such as checking the external storage media or taking backups of data. A UNIX system may have one or more printers. The printers are generally high - speed printers capable of printing over 300 lines per minute. In multi-user systems, which have only one printer, there may be situations where more than one user has given a print command at the same time. In such cases, the files that have to be printed out are queued up by temporary storage in one disk file, from which each file is printed out in sequence. This operation is called "Spooling" (Simultaneous Peripheral Operations On-Line). If a terminal is a PC or a PC-XT, it may have a local printer connected to it.

Key to Unix_Notes

Embed Size (px)

Citation preview

Key to Unix

Page 1 of 63

1. Introduction to UNIX1.1. Single-User SystemsThe personal computer (PC) is a small, general-purpose system that can execute programs to perform a wide variety of tasks. The PC, however, was designed for use by one person at a time; that is, it is SingleUser oriented with MS-DOS as the de facto standard operating system for this range of machines. Single user systems became very popular due to the low cost hardware and wide range of software available for these machines.

1.2. Multi-user SystemsAs opposed to single-user systems there are also larger systems, which more than one person can use at any time. Such systems are referred to as multi-user systems. Multi-user systems would be required when a number of applications have to be run simultaneously, or common resources, like printers and disks, are to be shared by a number of users.

1.3. Hardware - Multi-user Systems.While the hardware components of a multi-user system are similar to that of a single-user system, the following differences should be noted: The CPU of a multi-user system is more powerful and has capabilities to support multi-programming and multi-tasking, two features essential for multi-user systems. The hard disk of a multi-user system is bigger in capacity. Most multi-user systems use magnetic tape as external storage for backup of software. Single-user systems use floppies as the backup device. This is because multi-user systems have large hard disks, which have to be backed up quickly and conveniently. Each user communicates with the system through a keyboard and a VDU - these are together referred to as the user terminal or node. A terminal may also be a PC or PC-XT. The terminal is connected to the system unit by cables through RS232 ports. The number of terminals varies between systems. In multi-user systems, there is one terminal designated as the console. The console consists of a Keyboard and VDU connected to the CPU directly through cables. From the console, the operation of the system is controlled. When power is switched on for the system unit, messages regarding the boot procedure appear on the console only. After the boot procedure is over, all the users can start working at their terminals. The console is also used to send messages to the users of the system and for other operations such as checking the external storage media or taking backups of data. A UNIX system may have one or more printers. The printers are generally high - speed printers capable of printing over 300 lines per minute. In multi-user systems, which have only one printer, there may be situations where more than one user has given a print command at the same time. In such cases, the files that have to be printed out are queued up by temporary storage in one disk file, from which each file is printed out in sequence. This operation is called "Spooling" (Simultaneous Peripheral Operations On-Line). If a terminal is a PC or a PC-XT, it may have a local printer connected to it.www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 2 of 63

The system unit may be connected to user terminals located at remote sites or to remote system units through "Communications lines". Thus, a terminal of one multi-user system can communicate with any other multi-user system for sharing a database or sending important information. Just as a PC has serial ports to connect to a serial printer, so also multi-user systems will have special communication ports to link one system with another.

1.4. Classes of Multi-User Systems.Multi-user systems are classified into two broad categories: Mainframes Minicomputers

1.5. Multi-User Operating System - UNIXMulti-user operating system is expected to perform various functions, which can be broadly categorized as: Command Interpretation - involves accepting and getting executed user Instructions one by one. Peripheral Management - deals with handling all the input-output operations performed by the peripheral devices of the system. Memory Management - is the extremely important job of allocating memory for various jobs being performed on the system and even disposing of useless data in memory after it has been processed and used. Process Management - is important if several programs have to run concurrently in the memory. In that case, the OS has to ensure that all programs are rescheduled properly and no one program gets more than its fair share of CPU time. Multi-user operating systems are expected to handle multiple users as well as multiple peripheral devices concurrently. Such operating systems have to be more efficient and sophisticated than simpler singleuser operating systems. MS-DOS was designed for the PC with the assumption of a single end user. It was intended to be functional and friendly. UNIX was designed for a multi-user system. It was intended to be an environment for programmers and was therefore by design made powerful and terse. While programmers find UNIX very friendly, end-users find UNIX commands very cryptic and unfriendly.

1.6. STALLMAN AND TORVALDS: GNU AND LINUXUnix has finally turned commercial, but then two gentlemen, Richard Stallman and Linus Torvalds has different ideas. Both of them strongly felt that Unix was so good that it must be given any free. Stallman is the founder and prime mover of the Free Software Foundation (formerly known as GNU, a recursive acronym which stands for GNUs Not Unix!). GNU has practically every Unix utility of this own, but is best known for the emacs editor, the gzip compression utility and the gcc C compiler. It also has xFree86, its own X Windows system that is used by practically all implementations of Linux. Many of the GNU tools have been ported to the major flavours of Unix.

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 3 of 63

Linus Torvalds is the father of Linux, the free UNIX that is now making significant inroads into the commercial world. It came into being in 1991 when Torvalds, then a student at the University of Helsinki (Finland), made the entire software available on the Internet. This offering also included the complete source code that encouraged hundreds of programmers to add to it and make changes. Linux is distributed under the GNU General Public License, which makes it mandatory for developers and sellers to make the source code public. The license also lets you buy one copy of Linux and load it on a thousand machines (or more). Linux is particularly strong in networking and Internet features, and is an extremely cost-effective solution in setting up a web site or a local intranet.

1.7. History of UNIXUNIX is the most popular operating system on multi-user systems. This operating system originated as a single-user system. It started off on a cast-off DEC PDP-7 at Bell laboratories in 1969. Ken Thompson, with ideas and help from Dennis Ritchie, and others, wrote a small, general-purpose operating system, which included utilities to manage files and processes on the PDP-7, among other utilities. The system developed was so good that it attracted a large number of enthusiastic users and eventually enough credibility for transferring the system on to a larger machine, the PDP-11/20. In 1973, Thompson and Ritche rewrote the UNIX operating system in C, breaking away from the traditional system software language, Assembly. Around 1974, it was licensed to universities for educational purposes and a few years later UNIX was made commercially available. It is important to note that MS-DOS was created much after UNIX, by which time the industry had begun to accept UNIX as the standard operating system. UNIX features have therefore influenced the design of MS-DOS. All multi-user systems do not operate on UNIX, by which time the industry had begun to accept UNIX as the standard operating system. UNIX features have therefore influenced the design of MS-DOS. All multi-user systems do not operate on UNIX. Examples of other multi-user operating systems are: - VMS (Virtual Memory System) for VAX machines. - MVS for IBM mainframes Etc.

1.8. Features and Benefits of UNIXThe UNIX operating system is available on machines with wide range of computing power, from microprocessors to mainframes, and on machines across different manufacturers product lines. No other operating system can make this claim. The popularity and success of this is due to the following reasons. Portability The system is written in a high level language making it easier to read, understand, change, and move to other machines. Customers can now choose from over a wide variety of hardware vendors without being locked in with a particular vendor. Machine Independent The system hides the machine architecture from the user, making it easier to write applications that can run or micros, minis, and mainframes. Multi-user operations

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 4 of 63

UNIX is a multi-user system designed to support a group of users simultaneously. The system allows for the sharing of process power and peripheral resources while at the same time providing excellent security features. Hierarchical file system UNIX uses a hierarchical structure to store information. This structure has the maximum flexibility in grouping information in a way that reflects its natural state. It allows for easy maintenance and efficient implementation. Unix shell UNIX has a simple user interface called the shell that has the power to provide the services that the user wants. It protects the user from having to know the intricate hardware details. Pipes and filters UNIX has facilities called pipes and filters, which permit the user to create complex programs from simpler programs. Utilities UNIX has over 200 utility programs for various functions. These utilities form a powerful set of tools to cater to user requirements without the necessity of writing new programs. Background Processing UNIX has facility which the user can start a task and then proceed to work on other tasks while the system runs the first task in the background and the second task in the foreground. Background processing helps the user in effective utilization of time. Software Development Tools UNIX offers an excellent variety of tools for software development for all phases, from program editing to maintenance of software. Maturity UNIX is a time-tested operating system. It offers a bug free environment and high level of reliability.

The UNIX SYSTEM supports a wide variety of languages - C, Fortan, Basic, PALCAL, Ada, COBOL, Lisp and Prolog.

1.9. Versions of UNIXOne of the major attractions of UNIX has always been the capability to shape it to meet a variety of needs. This flexibility led to a proliferation of different versions of UNIX. In addition to several versions of UNIX from AT&T, hardware and software venders have adapted UNIX from microcomputers to mainframes. Some of the popular versions of UNIX are: Version UNIX System UNIX BSD(4.xx) XENIX ULTRIXwww.wilshiresoft.com

Developed AT & T Berkeley Software Distribution of Berkeley University Microsoft for micros DEC for minisWilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 5 of 63

AIX

IBM

1.10. THE KERNEL AND SHELLThe entire UNIX system is supported by a handful of essentially simple concepts. Foremost amongst is kernel and shell

The kernel is the heart of the system- the core of the UNIX system is the Kernel- the operating system program. The kernel controls the computers resources, allotting them to different users and to different users, decides process priorities and performs all the tasks, which the user wouldnt like to bother about. It interacts directly with the system hardware. There is only one kernel for any system. Kernel, in traditional parlance, is often called the operating system. SHELL USERSYSTEM SW UNIX COMMANDS

HARD WARE

DATABASE PACKAGES

COMPILERS

SHELL

The Structure Of The Unix System The shell, on the other hand, is technically a UNIX command. It is the interpreter of user request. Computers dont have inherent capability of translating commands into action. An interpreter is required, and that job in the UNIX system is handled by the shell. It takes the commands from the user, deciphers it, and by exchanging information, and sends that command to the kernel. It is actually interface between user and kernel. It has a programming capability of its own.

1.11. Security for the Unix UserThe UNIX system can be used only by those persons who maintain an account with the computer. This list of accounts is maintained separately in the computer. You cant simply sit down at any terminal and start banging away if your name doesnt feature in the list. That would be both inadvisable and an impossible thing to do. When the system prompts you with Login: message, it expects a response from you. Curiously enough, you can say that the Login message indicates that the previous user is logged out, i.e. has terminated his session. You are now expected to enter a special user name or account, which has beenwww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 6 of 63

allotted to you by your system administrator. This user account is maintained by the system to check for illegal responses. So, you have to ask your administrator for your account name. NOTE:-The system never indicates what went wrong- the login name or the password. This procedure followed by users to start a UNIX session- the login procedure-has been explained earlier. The login procedure ensures that only authorized users can try to access the system. However, it is easy for anyone to find out a users login name since this is displayed on screen when being entered. Thus the login procedure is not a foolproof system. To overcome this problem, UNIX allows a user an additional measure of security by allowing him to have a password associated with his name. To login using password-protected user names, the user has to enter not only the user name but also the password. UNIX to see if they are authorized entries checks the combination of the two. The $ prompt appears only if the user has entered both the name and password correctly, otherwise he is asked to reenter the user name followed by the password. Passwords are not displayed on the screen while they are being entered. Sample login sequence is show below:

(Password is entered correctly)

(Password is entered incorrectly)

Note that the user name and password are checked only after both have been entered.

1.12. Creating a PasswordA user can add a password for has login name by the passwd command. Shown below the passwd command executed by the user Gopal:

$ passwd Changing password for gopal New password: Re-enter new password: (user enters the desired password) (to double-check the new password)

The user is asked to re-enter the new password for confirmation. If this entry differs form the earlier entry, and then UNIX does not accept the password.

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 7 of 63

If the user entries match, then the password is associated with the users name. Subsequent attempts to login will require that the user enter his password

1.13. Rules for PasswordsA user password in UNIX Cannot be less than 6 and more than 14 characters long Can contain any character in the keyboard character set Must contain at least 2 alphabetic characters and at least 1 numeric or special character.

It is desirable to have slightly complex passwords so that they are not easily deciphered. The use of simple passwords has in fact become a major cause for concern in the U. S. A, where there have been many incidents of unauthorized access to a UNIX system simple because users used very simple and obvious passwords such as their own names, or birth dates or age.However, passwords should not be so complex that they cannot be remembered.

1.14. Changing the Password.A user can also change his password with the passwd command. The steps followed by the user Gopal to change his password are depicted below:

$passwd Changing password for Gopal Old password: New password: Re-enter new password: $_

The passwd command asks for the old password to ensure that the authorized user (and not just anyone) is trying to change the password.In case UNIX does not recognize the old password, it displays a sorry message and the $ prompt appears on the screen.

$passwd Changing password for gopal Old password: Sorry. $

If the old password is entered correctly, then the user is asked to enter the new password and re-enter it to confirm. If the two entries do not match, then the user is given another chance to enter the new password.

$passwd Old password: New password:www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 8 of 63

Re-enter new password: They do not match, try again. New password: Re-enter new password: $

When changing the password, the new password should differ from the old password by at least 3 positions.

1.15. Check your current Directory the pwd commandCOMMAND: pwd (present working directory) FUNCTION: The pwd command gives the absolute path name of the users current directory place in the current place in the structure.

Ex: $pwd /usr/user1$_

Here, /usr/user1 is the directory in which the user user1 is presently working.

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 9 of 63

2. The UNIX File System2.1. The FILE in UNIXA Unix file a storehouse of information- it is simply a sequence of characters. UNIX places no restriction on the structure of a file, and you dont need to assume a predefined structure to work with it. A file contains exactly those bytes that you put into it, whether it represents a source program, other text or executable code. Unix file does not contain the end-0f-file mark. In UNIX, all information is treated as a file. So, besides a users program files and data files, there are also special files such as files that contain information about directory contents or files that store information about various input-output devices connected to the system. In UNIX, devices is also treated as a file, i.e., all information going to, say the VDU, is treated as if it were being set to a file.a. Ordinary files - All files created by a user come under this category of files. These include all data files, files containing programs, complied and executable program files. A user can make changes to such files. b. Directory files - A directory is storehouse of information about the file and subdirectories in that directory. For each directory there is file, by the same name as the directory, which contains information about files under that directory. For example, for the directory /user/gopal, there will be a directory file called gopal in the directory /user, which contains certain information on all the files and directories under the directory gopal.

c. Device files - Most of the system files in UNIX are special files. The device file is special in the sense that any output directed to it will be reflected onto the respective I/O (input/output) device associated with the filename. Special files are typically associated with input-output devices. Such files are found in the standard UNIX directories such as /dev and /etc. Users cannot alter special files.

2.2. THE STRUCTURE OF THE FILE SYSTEMAll files in UNIX are related to one another. The file system in UNIX is a collection of all these related files (ordinary, directory and device files) organized in a hierarchical (an inverted tree) structured

Root(/)

bin

dev

etc

mnt

tmp

unix

lib

var

bin

kumar

sharma u1001p

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 10 of 63

The UNIX file system

The directories shown directly under root are normally found in very UNIX system, in-addition to others

Root is actually a directory file, and it has a number of sub-directories (or branches) under it. These subdirectories, in turn, have more sub-directories and other files (leaves) under them. For instance, bin and usr are two directories directly under root, while a second bin and kumar are sub-directories under UNIX.

NOTE: -

It is possible for two directories to have the same name. Every file, apart from root, must have a parent, and it should be possible to trace the ultimate parentage of a file to root. It is not possible that the two directories or files have the same name in one level.

2.3. Displaying the file TypeFile-names and directory names are displayed using the ls command.

For example: $pwd

/user/asha $ls Z.c alpha-doc asha1 asha2 tempdir x.c $

From this listing, it is impossible to tell whether asha1 is a directory file or an ordinary file or a special file; whether tempdir is actually a directory file as its name indicates.

UNIX provides a way of doing so by using the l option of ls command this is shown below:

$ pwd /user/asha $ ls l total 6

This ls l command shows a long listing for files in the current working directory with:

The file-names on the extreme right.Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

www.wilshiresoft.com

Key to Unix

Page 11 of 63

The file type as the first character on the extreme left. a hyphen in this position indicates an ordinary file d in this position indicates a directory file Special files will be indicated by either b,c or p in this position. These indicate different categories of special files a total maintained by the system.

2.4. Creating DirectoriesCOMMAND: mkdir (make directory)

FUNCTION: It creates a new directory specified as argument, under the current directory.

Ex:

$pwd /usr/user1 $mkdir dir1 $_ $pwd $/usr/user1 $_

The new directory dir1 is created under the current directory called user1. Creating a directory does not change the users position in the tree structure.

2.5.Changing DirectoriesYou can move around the file system by using the CD (Change Directory) command.

COMMAND: cd (change directory)

FUNCTION: The command changes the directory to the directory specified as argument.

Ex:

$pwd /usr/user1 $cd dir1 $ pwd /usr/user1/dir1 $_

Here, the cd command changes the directory /user/user1 in to the sub-directory called dir1.

The cd command used without arguments gets the user back to his HOME directory from wherever he is.

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 12 of 63

To get back to the parent directory, the special argument . . (dot-dot) is used with cd. The symbol . always means the parent of the current directory .

2.6. The ls commandCOMMAND: ls FUNCTION: Lists names of files in the current directory. You can list out the files and subdirectories in different directories by specifying the absolute path after ls command. Ex: $ls

ls stands for lists . It lists the names of files and sub-directories in the current directory. It has number of options, which can be given as arguments. It also sorts the names of the files alphabetically by default.

Some Options with ls:Options -a -l Description Listing all matching entries including hidden files Provides a long listing showing seven attributes of a file. Sorts files in reverse order. Recursive listing of all files in sub-directories. Displays the number of blocks used by a file. Sorts files by modification time. Displays information about a particular directory. It differentiates a file and directories by appending a / at the end of directory names It displays the inode number of a file. (inode number is the unique number given to a file) Sorts by time of change of the I-node

-r -R -s -t -d -F

-i

-c

2.7. Listing the contents of the file:COMMAND: cat (concatenate files) FUNCTION SYNTAX Ex: $cat file1 : Displays the contents of one or more files. : cat

A sample file.Good bye. $_ Here, the contents of the file file1 are displayed on the screen using cat command. You can concatenate two files using cat commandwww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 13 of 63

$cat file1 file2 >file3 $_

Here, the contents of file1 and file2 are displayed and they are redirected to the file3. File3 contains the contents of file1 and file2. If file3 is already exists it simply over writes the file. Using cat command you can create file

$cat>file4

Here `cat command takes the input from the keyboard and redirects the output to the file4. After entering the text you have to press `ctr+d` to save and come out of that file. NOTE: The [Control-d] OPTION is used to terminate all input not only with cat, but with several other commands as well.

2.8. Removin DirectoriesCOMMAND: rmdir (remove directory) FUNCTION: This command removes the empty directory. Ex: $ rmdir dir1 Here, dir1 is the directory under the current working directory. It should not be the current working directory. rmdir command removes the directory only if the directory is empty. NOTE:-A sub-directory cannot be removed with rmdir unless it is empty and one is positioned in its parent directory.

2.9. Relative PathNamesSuppose you have just changed your directory to /unix2/u1002/abc. To switch to your home directory, you can always use the absolute pathname: $pwd /unix2/u1002a/abc $cd /usr/kumar $ pwd /usr/kumar

$Every absolute pathname must trace its origin to root, as discussed earlier in this chapter. The first /indicated root directory, while subsequent ones act as delimiters to sub-directories. This method can be inconvenient and tedious, especially when the absolute pathname is quite long i.e., when you located a number of generations away from root. If you have a long chain of sub-directories, then the use of an absolute pathname is an unsatisfactory solution to the problem of moving a single generation up the hierarchy. UNIX also permits use of a relative pathname, which locates a filename with respect to the current directory. In ls command you discovered two hidden directories--. and.. Indicating the current and parent directory, respectively. Using. . As an argument to cd, you can issue an instruction to move to the parent directory /usr/kumar/dir1/data/text, i.e. the directory /usr/kumar/dir1/data:

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 14 of 63

$ pwd /usr/kumar/dir1/data/text $cd .. /usr/kumar/dir1/data $_ This method is compact and more useful when ascending the hierarchy.

2.10. Copying files:COMMAND FUNCTION SYNTAX Ex : cp (copy) : This command duplicates the file. : cp : $ cp file1 file2

The cp command copies the source file to the target file if the target file is already exist in that directory. Ex: cp i file1 file2Here i, option allows you to copy the files interactively. If file2 exist than it will prompt you to over write the file.

Note: using cp command you cannot copy multiple files to a single file.

2.11. Moving or Renaming files:COMMAND: mv FUNCTION: Renames or Moves a file/directory. SYNTAX : mv

Ex: $ mv file1 file2

Here, file1 is renamed with file2 In UNIX, a file can also be moved to another directory as shown below. Like cp, mv also overwrites the file, if the target file is exist. Ex: $ mv file1 /usr/user1/dir1

2.12. Removing Files:COMMAND: rm (remove) FUNCTION: Removes the files from current directory. SYNTAX: rm

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 15 of 63

Options -I

Significance Interactive rm prompts for confirmation before each file is removed. Forcibly removes files permission on them. that dont have write

-f

-r

Recursive rm searches for files in sub-directories also.

2.13. File SecurityPassword security protects a system from access by an unauthorized person. In a multi-user system, each authorized user can have access to files that belong to other users or to the system files and utilities. In such an environment, it becomes essential that files should be protected so that another user does not misuse one users files and system files are not detected or modified.

UNIX allows users to protect their own files from other users working on the system. It also provides protection for system files. Before an explanation of the method of protecting their own files from other users working on the system. It also provides protection for system files.

Before an explanation of the method of protecting files, the following concepts will be discussed:

The types of files in UNX The concept of File Owner, Group Owner and Other Users. Files access permissions.

2.14. The File Owner, Group Owner and Other Users File OwnerThe user who creates a file is said to be the owner of that file. The owner of a file can perform any operation on that file, e.g. copying, deleting, and editing (through some editor) etc.

Group OwnerConsider the following situation: A project team of 5 people of the SMARTEST CONSULTANTS PVT. LTD. is working on a software development project for a private detective agency. The team is headed by an analyst. The other 4 members are all programmers. The team is working on a UNIX system. Each programmer has been given a few programs to develop. The data, provided by the detective agency, is of a highly confidential nature, and so the data file has been created in the analysts HOME directory. One programmer may have to link his program to another programmers program in order to test his program. In this situation, each programmer is the File Owner of his own program files. Each program, however, would also belong to the other programmers, so that they could use the programs for linking. The project team (of 5 users) is said to be the Group Owner for the file.

In UNIX, it is possible to define which user of the system is member of a group. A group of users are also given a name, just as a user is given a name.www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 16 of 63

So, for the project team, the programmer Anita may be the owner of her program files. The group of users in the project team may be called PROJECT-ABC, which becomes the Group Owner of Anitas program files.

Other UsersIn the example of the SMARTEST CONSULTANTS PVT. LTD., all users of the system who are not members of the group PROJECT-ABC are referred to as Other Users for all files that belong to that group. Their Other Users are thus those users who do not have any common needs for data or programs with the Group Owner. For e.g. people of the accounts department who use the system to generate reports, or data entry operators entering data for payroll can be referred to as Other Users for the files that belong to the group PROJECT-ABC. To summarize: Associated with each file in UNIX is: a File Owner a Group Owner which consists of users who need to share that file Other users who do not belong to the group.

UNIX stores this information for each type of file on disk.

2.15. FILE SECURITY THROUGH FILE ACCESS PERMISIONS (FAP)UNIX follows three-tired file protection system, which determines the access rights that you have for a file. Each tier represents a category, and consists of rs,ws and xs to represent three types of permissions. UNIX allows the owner of a file to define how the file can be accessed by:The file owner himself The group owner of the file Other users The file Owner can define the following kinds of permissions for each of the above user categories: a) Read access If a user has read access permission for a file then he can display the file, copy it compile it etc. b) Write access If a user has write access for a file then he can write on to it, change its contents or delete it. c) Execute access The user can execute the file if he is allowed execute access.

The permissions of each file are stored as follows: 1. 2. 3. The permissions are given in the first column from the second position The first three characters show the read, write and execute permissions for the file owner the next three are the permissions of the Group owner and the last three are the permissions of the Other users. If a permission is allowed to a user, then r (read), w (write) or x (execute) is displayed otherwise a hyphen appears in the place. Cd ls Cp Into X X X X X cp from X X

Directory Permissions for groups and others r--w-

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 17 of 63

--x rwr-x -wx rwx

X

X X

X X X

X X X

The FAP for a directory is interpreted in the following way:

No read permission

Does not allow the user : To list the contents Remove the directory using rm r.

No write permission

Does not allow the user : Copy the files to the directory. Remove the files in the directory. Rename files in the directory. Make a sub-directory. Remove a sub-directory from the directory. Move files to and from the directory.

No execute permission

Does not allow the user: Display the contents of directory file from within the directory Change to that directory. Display a file in that directory. Copy a file to or from a directory.

2.16. Changing the FAP for the File Owner, Group Owner and other users:To control the access permissions for a file for different users, the File Owner can use chmod command.

The following example shows how the file access permissions for the file file1 can be changed. The permissions for this file are shown below:-rwxrwxrwx 1 vara unix2 20 jan 31 10:40 file1

To change permissions for all the three categories of users, the file owner has to indicate:www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 18 of 63

-

Which permission is to be changed? Whether the permission is to be given or removed. The file for which the permissions are to be changed.

SYNTAX: $chmod

filename

For example: The file Owner can remove the write permission for all users for the file file1 by the following command: $chmod $_ The FAP for the file file1 will now appear as follows: -r-xr-xr-x 1 vara unix2 20 jan 31 10:40 file1 -w filename

Note that in place of all Ws, hyphens have appeared. To add back the write permission, the File Owner can give the following command:

$chmod

+w

file1

$_

More than one-file access permissions can be changed in one command (instead of using two or more commands).

For example:

$chmod

+wx $_

file1

This is done by specifying one of the following before the + or sign in the command.

u

for changing FAP for File Owner only example : chmod u+r x.c

g

for changing FAP for Group Owner only Example : chmod g-r x.c

o

for changing FAP for all Other Users only Example: chmod o+x x.c

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 19 of 63

3. Unix Utilities3.1. The wc CommandThe wc filter counts the number of lines, words and characters in the specified file or files. It is capable of accepting input directly from the keyboard. By entering wc without any arguments, it waits for the user to type in the input. By default, wc prints all the three counts lines, words, bytes. It comes with three options, which allow user to obtain the number of lines, words or characters individually or in any desired combination.

Options -c

Significance Counts the number of characters in the given file

-w

Counts the number of words in the given file

-l SYNTAX : wc [options]

Counts the number of lines in the given file.

Ex:

Assume the file file1

$cat Raju Rani Vara Sai

file1

$ wc

file1 4 4 19 file1

In the above example, it displays the number of lines, words and number of characters along with the filename.

Ex:

$ wc

-l 4

file1 file1

$_ Ex: $ wc -c 16 $_ file1 file1

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 20 of 63

3.2. The pg Filter:This Filter is used to display a large file, one screen full at a time. The format of the pg command is : SYNTAX: $pg filename Ex: $pg file1

3.3. The more Filters:While viewing large files, you often find the output scrolling off your screen. This sometimes happens so fast that, before you hit [control-s] to stop it, quite a bit of the output would have scrolled off. Using [Control-s] and [Control-q] alternately is certainly not a comfortable method of halting the output. It also doesnt let you see what has already been seen before. UNIX offers the more command as a paging tool, so that you can view one page at a time. The Syntax of the more command is as follows: $more

Here, more allows the user to view a file, one screen at a time.

3.4. PipesUNIX has a feature by which filters and other commands can be combined in such a way that the standard output of one filter/command can be sent as standard input to other filter/command. The vertical bar (|) is the pipe character.

Let us now see some examples of piping:

1)

$ls | wc

Here, the output of ls command becomes the input to wc which promptly counts the number of lines it receives as input and displays this count on the screen.

1)

$ who | sort Here, instead of displaying the output of who to the screen it is piped to sort. Sort sorts whatever it receives as input and displays the sorted output.

3.5. The man command displays pages from the UNIX reference manualFor Example, if the user wants detailed information about the ls command, the command to be given is: $man ls NAME : Command/file name, along with a brief description SYNOPSIS : How to use the command, it contains the optional and non-optional arguments. DESCRIPTION : An explanation of how to use the command, and also an explanation of each option. EXAMPLE : gives example of how to use a command. FILES : files which have to be available for this command to work SEE ALSO : commands similar in purpose DIAGNOSTICS : Explanation of error messages WARNINGS : Things to be careful about when using the command BUGS : Known problems and suggested improvements.

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 21 of 63

3.6. Comparing two FILES The CMP CommandFrequently, you may require knowing whether two files are identical in all respects so that one of them can be deleted. The cmp (compare) command is used to achieve this task. When used without options it uses two filenames as arguments, and displays the differences on the terminal: $cmp file1 file2 file1 file2 differ: char 9, line1 The two files are compared byte by byte, and the location of the first mismatch is echoed to the screen. If two file are identical then cmp displays no message, but simply returns the $ prompt follows the UNIX tradition of quiet behaviour. The cmp l option gives a detailed list of the byte number and the differing bytes in octal for each character that differs in both the files.

3.7. The comm-command further comparisonComm. Compares two sorted files and compares each line of the first file with its corresponding line in the second. It displays a three-columnar output. The first column contains lines unique to the first file, while the second column shows the lines unique to the second file. The third column displays lines common to the both files. Try using it on the two files file1 and file2, but have a look at their contents first: $ cat file1 c. s .das singhvi chanchal sumitha roy Krishna murthy Satish kumar $$cat file 2 barun gupta c. s. das anil kumar smitha chowdary sumitha roy $-

$ comm. File1 file2

anil kumar barun gupta Krishna murthy Satish kumar Singhvi chanchal Sunitha chowdary sunitha roy c.s. das

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 22 of 63

3.8. The diff commandDiff is the third command, which can be used to display file differences. But like its fellow mechanism cmp and comm., it also tells you which lines in one file have to be changed to make the two files identical. It has a similar syntax and has a few options. When used with the same files, it produces a detailed output. Diff uses certain special symbols to indicate the changes that are required to make two files identical.

3.9. The banner commandThe banner command creates posters by blowing up its argument on the screen. On each line it can display a maximum of ten characters. If you are to display the word UNIX on the screen, then this is how you can use this command: $banner UNIX This command is placed in /usr/games directory.

3.10. The calendar commandThe cal command is quite useful in printing the calendar of any particular month or the year. Any calendar from the year 1 to 9999 can be displayed with this command: $ cal 2001 This command displays the calendar of the year 2001. $ cal 01 2001 This command displays the calendar for the particular month of January 2001 The cal command is accurate, and also takes into account the leap year adjustments that took place in the year 1752.

3.11. Displaying the SYSTEM DATE with Date CommandThe UNIX system maintains an internal clock, which is meant to run perpetually. This is possible because, when the system is shut down, a battery backup keeps the clock ticking. This clock actually stores the number of seconds elapsed since January1, 1970. It is used to time stamp a file. You can simply display the current date with the date command, which shows the date and time to the nearest second. $date Tue sep 19 10:13:52 BST 1995 You can use different options with date command to display the date in different formats.

Date +%m Date+%h Date+%y

Displays only the month of year Displays only the month in character Displays only the year

3. 12. The who commandUNIX maintains an account of all the current users of the system. It is a good idea to know the people working on the various terminals so that you can send them messages directly. A list of them is displayed by the who command, which, by default, produces a three-columnar output :

$whowww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 23 of 63

root kumar tiwary

console tty01 tty02

jan jan jan jan

30 30 30 30

10:32 14:09 14:15 13:17

Sharma tty05

-H option with who command displays the heading for each column The who command, when used with the arguments am I, displays a single line of output only, i.e., the login details pertaining to the user who invoked this command: $ who am I kumar tty01 jan 30 14:09

3.13. Wild-Card MatchingUnix, offers the facility to perform an operation on a set of files without having to list out the names of all the files on which the operation has to be performed. This is made possible by the use of certain Special characters in the command in the place of the actual filenames. UNIX interprets these special characters as a specific pattern of characters. UNIX then compares all filenames under the directory specified in the command to find out which filenames match that pattern. The command is executed on files whose names match that pattern.

Wild-Card *

Significance Matches one or more character or a string of more than one character. Matches exactly one character.

?

[]

Matches exactly one of a specified set of characters.

3.14. The * Wild-Card:This Wild Card is interpreted as a string of one or more characters (or no characters). It can be used with other characters. It can also be repeated in the command line.

Ex: $ls file* file1 $_ file2 file3 file4 fileabc file

When * (asterisk) is appended to the string file, the pattern file* expands in to all files, in which the first four constitute the string file and after this four characters it can be anything or nothing i.e. the above command lists all files in the current directory as shown above.

The * Wild-Card can also be repeated as shown below:

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 24 of 63

Ex: Assume that files, file1.txt, file2.txt, file3.abc already exists and gives the command$ls file*.* file2.txt file3.abc

file1.txt $_

This displays the files starting with file and containing any sequence of characters or no characters followed by a . (dot) and then followed by any sequence of characters or no characters .

3.15. The ? Wild-Card:The ? Wild Card matches exactly one occurrence of any character. It can be used with other Wild Cards. It can be in the command line. Ex: Assume that the files a, b, c, file1, file2, file1.txt, file2.c already exists in the current directory.

1) $ls ? a $_ The ? matches exactly any one character. Here all the files whose names are of single character are displayed. 2) $ls file? file1 $_ file2 b c

3)$ls *.??? file1.txt $_ 4) $ls file2.? file2.c $_

In the second example, it is listing all files with a pattern file and followed by any single character i.e. file1 and file2. In the third example, it is displaying for any file with a. (dot) extension of three characters. In fourth example, it displays the files with pattern file2 and with a . extension of a single character.

3.16. The [ ] Wild-CardThis [ ] Wild-Card matches any one of a specified set of characters which are given within the brackets. It can be used with other Wild Cards. A single character expression, taking the values 1 or 2 or 3 can be represented by the expression [123]. This can be combined with any string or other Wild-Card expression.

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 25 of 63

Ex: Assume that the files a, b, c, d, file1, file2, file3 exists in the current directory.1) $ls [abc] a $_ It displays the files with single characters of either a or b or c. b c

2) $ls file[13] file1 $_ file3

All the above Wild-Cards can be combined with each other. Ex: 1)$ls *.??? It will display files with pattern anything with the . (dot) extension of three characters. 2)$ls [a-z]* It displays all files starting with a to z and anything or nothing afterwards. 3)$ls [!a-c]* It displays all the files which do not start with a or b or c.

3.17. RedirectionMost UNIX commands perform one simple function, which consists of the following steps :- They take some data as input from some source - They process the data - They produce the results as output and send it to some destination In UNIX, when a user executes a command, the shell runs the command and assigns to the command: - The terminal keyboard as the source of input - The terminal VDU as the destination of output

In UNIX keyboard and VDU are referred by special names - the keyboard is the Standard input file and the VDU is the Standard output file. Consider the cat command. When followed by the file name, this command displays line by line from that file, tills the end of the file. Without the file name it takes its input from the standard input file and writes its output to the standard output file. The cat command waits for the input from the keyboard. When the user presses the key after entering a line, the cat command does what it is supposed to do - simply displays the entire line on the screen. The user can keep on inputting lines. To indicate the end of input, the user has to press d Not all commands use the Standard input file for input and the Standard output file for output. Given below are examples of the commands that use one or neither of these files. a. Command that uses neither the Standard input file nor the Standard output file.www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 26 of 63

E.g. cd - does not except input from the keyboard - does not write anything onto the VDU.

b. Command that uses the Standard output file but not the Standard input file.E.g. pwd - does not expect input from the keyboard - displays its output ( the name of the current working directory) on the VDU.

3.18. Standard ErrorWhen an invalid command (e.g. a command entered incorrectly or with invalid options) is given, UNIX displays appropriate error messages on the VDU. The VDU is thus also the Standard error file.

file descriptor 0 1 2 Ex: $ls>abc Redirects the output of ls command to abc file$ls -l 2> abc

Device Files Stdin Stdout Stderr

Redirection operator < > >

Redirects the error messages of the command to abc file $ls -l > abc 2> err Redirects the output if any to abc and the error messages of the command to err file.

3.19. The two special files- /dev/null and /dev/ttyQuite often, you may like to test whether a program runs successfully without seeing the output or the error messages. You make not like to save them in files either. You have a special file which simple accepts any stream without growing in size; it is the file /dev/null. $ cal 1995 >/dev/null $ cat /dev/null $_ The device file /dev/null simple incinerates all output directed towards it. This facility is useful in redirecting error messages away from the terminal so that they dont appear on the screen. /dev/null is actually a pseudo-device because, unlike all other device files, it is not associated with any physical device. The second special file that you can hope to find in the UNIX system is the one indicating ones terminal, /dev/tty. Consider, for instance, that kumar is working on the terminal /dev/tty01, and Sharma on /dev/tty02. But both kumar and Sharma can refer to their own terminals as /dev/tty. Thus, if kumar issues the command $who >/dev/tty The list of current users is sent to the terminal kumar is currently using i.e. /dev/tty01. Similarly, Sharma can use an identical command to see the output on this terminal. NOTE: - THE SIZE OF /dev/null is ALWAYS ZERO

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 27 of 63

4. Simple Filters4.0. Filter:A filter is a command or a user program that takes its input from standard input, filters the input and sends output to the standard output. These are file-related commands.

4.1. The Sort Filter:The sort filter arranges each line of input in ASCII order. As the name suggests the sort command can be used for sorting the contents of a file. While sorting, the sort command bases its comparisons on the first character on each line in the file. If the first character of two lines is same then the second character in each line is compared and so on. That is it sorts the spaces and the tabs first, then the punctuation marks followed by numbers, uppercase letters and lowercase letters. SYNTAX: sort [options] Ex: when the sort command is invoked without options, it sorts the entire line. Consider the following example:

$sort

Anitha Swapna Madhu d Anitha Madhu Swapna $_

The user enters names, each on one line. When the user indicates end of input by pressing d, sort compares the corresponding characters of each line and displays the lines in proper sequence. The following are the options with sort:

Options -t -n -r -f +n[-m]

Significance Specifies the field separator Sorts in numeric order Sorts in reverse order. Ignores case while sorting. Skips n fields before sorting and then sorts through field m. Sorts in dictionary order.

-d Stores output in file. The default is to send output to standard output.

-o file

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 28 of 63

4.2. Options of the sort Filter:1) The t option: Sort assumes that a space or a tab character separates fields. In this case, the -t option is used before filename to specify the field separator. For example, if the filenames contains fields separated by a hyphen (-) and the file is to be sorted on the third field, then the following command would be used:

$ sort

-t -

+2 -3

file1

Note that the field separator is enclosed in double-quotes.

2) The -n option: Since sort arranges its input in ASCII sequence, numbers would also be arranged so. To indicate to sort that the input is to be sorted according to numeric value of the numbers and not in ASCII sequence, the n option must be given in the command.

Ex:

$sort 6 5 8 2 9

-n

d 2 5 6 8 9 3) The r option: This changes the output of sort to reverse order. Consider the following example: Ex: $sort -r

Anitha Laitha Madhu d Madhu Lalitha Anitha

$_4) The -f option: In case the input is to sort consists of digits and alphabets and other characters, sort arranges data in ASCII sequence. In the ASCII sequence of characters, A-Z has lower values than the corresponding lowercase alphabets.www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 29 of 63

So, sort would place anitha after Anitha since a has higher ASCII value than A. The f option folds all lowercase characters into uppercase characters, i.e. it considers all lowercase characters as uppercase characters without actually changing them. Ex: $sort -f

Anitha asha rama Rama Prasad d asha Anitha Prasad rama Rama $_

5) The +pos1

-pos2 option:

By default sort assumes that fields are separated by a blank space or a tab character. To sort a file on one field, the position of the field in the file has to be specified. This is done as follows:i. ii. The number of field separators that have to be ignored to reach that field must be specified as +pos1 where the pos1 the appropriate number. The field separator at which sort is to stop must be specified as pos2 where the pos2 is the appropriate number.

For example, to specify sorting on third field, the user will have to specify +2 and -3 i.e. ignore the first two field separators and stop at the third separator. The sort command would then be as follows: $sort +2 -3 filename

6) The -o option: The output of sort always appears on the VDU (standard output file). In case, this output is to be saved on a disk file, the o option should be used. Consider the following example:$sort -o file2 file1

Here, the o option indicates that the output is to be sent to the file specified after it. The name of the file to be sorted is entered at the end of the command. o is followed by the name of the output to which the sorted data should be written.

4.3. The Cut FilterThe cut filter of UNIX is useful when a file has to be queried to display selective fields from a file. It cuts or picks up a given number of character or fields from the specified file. The cut assumes that a tab separates the fields. SYNTAX: cut [options] Options of the cut filter are: Option -fwww.wilshiresoft.com

Significance To indicate the fields to be displayed.Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 30 of 63

-d

To specify the field separator.

-c

To cut a particular range of characters.

1)

The -f option:

This option is used to specify the fields to be listed out. Consider the example: Ex: cut -f 1, 2 filename

Here, the name of the file whose fields are to be displayed is specified at the end of the command. The f option is followed by the number of each field to be displayed. The numbers are separated a comma. So, this command displays the first and second fields from the given file.A range of fields can also be specified with cut as shown in the following examples: cut -f 1,4 filename -cut -f1-4 filename -Displays first and fourth fields in the given file. Displays all the fields up to fourth field.

2)

The -d option:

The cut command assumes that a tab character separates the fields. If some character other than default tab character delimits the fields, cut supports an option -d, which allows to set the delimiter. The field separator must be enclosed in double-quotes.

Ex: Consider the file file1 may have the information for each student stored in the following format:Name: rollno: total: grade Each piece of information is separated by a colon, hence we require the field delimiter to be recognized as :. The command for listing the name and grade fields would now be: $cut -d : -f 1, 4 filename 3) The -c option: The option is used to cut the specified columns from a file. For example, UNIX $cut -c 2,4 filename As a result, the second column and the fourth column from each line in the given file would be displayed.

4.4. The head FilterThe head command, as the name implies, displays the top of the file. The simplest use of the command involves specification of the filename, without specifying the number of lines to be displayed. When used in this way, it displays the first ten records of the file. SYNTAX: $head filename

We can specify a line count and display say, the first three lines of the file. Use the - symbol, followed by a numeric argument as follows: Ex: $head - 3 filename Here, the first three lines of a file would be displayed.www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 31 of 63

4.5. The tail Filter:Complementing its head counterpart, the tail command displays the end of the file. If no line count is given, tail displays the last ten lines of the file. SYNTAX: $tail filename

Ex: $tail -3 filename

Here, the last three lines from the given file will be displayed.

4.6. paste command:This command prints the files side by side (i.e. horizontal merging as opposed to cat which does vertical merging.). SYNTAX: $paste file1 file2

Ex:

$cat file1 Akanksha Krishna $cat file2 6556688 7612214 $ paste file1 file2 Akanksha Krishna 6556688 7612214

4.7. The uniq command:In any EDP environment, there is often a problem of duplicate entries creeping in due to faulty data entry. You just saw how sort removes them with the u option. UNIX offers a special tool to handle these records-the uniq command. The command is most useful when placed in pipelines, and can be used as an SQL-type query tool. $cat dept.lst 01|kalyani|accounts|6213 02|satish|office|4214 01|kalyani|accounts|6213 03|murthy|office|4214 03|murthy|office|4214 $_ uniq simple fetches one copy of the redundant records, writing them to the standard output: $sort dept.lst|uniq 01|kalyani|accounts|6213 02|satish|office|4214 03|murthy|office|4214 uniq requires a sorted file as input, the general procedure is to sort a file and pipe the process to uniq. If uniq is to merely select unique lines, it is preferable to use sort u which does this job with a single command. But uniq has a couple of useful options; they can be used to make simple database queries. Uniq u option selects only the non-repeated lines: And the -c option displays the frequency of occurrence of all lines, along with lines: $ sort dept.lst | uniq cwww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 32 of 63

2 1 2

01|kalyani|accounts|6213 02|satish|office|4214 03|murthy|office|4214

4.8. Translating Characters - the tr commandtr is another important UNIX filter which maps character using one or two compact expressions. The syntax of this command is noted in the following. -tr The first difference that should strike you is that this command takes only the standard input as the source of its data; it doesnt take a filename as its argument. When invoked without options, it translates each character in expression1 to its mapped counterpart in expression2. The first character in the first expression is replaced by the first character in the second expression, and similarly for the other characters. You can use tr to replace | with a ~, and the / with a -, in the database file. $tr |/ /dev/null; echo $? 0 $ grep manager emp.lst>/dev/null; echo $? 1 $ grep manager emp3.lst>/dev/null;echo $?www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 52 of 63

grep: cant open emp3.lst 2 grep is one command which returns these values; 1 if the pattern cant be found, and 2 if the file cannt be opened

Shell Programming Constructs

9.11. if..then..else conditionThe if statement, like its counterpart in other programming languages, takes two-way decision depending on the fulfillment of a certain condition. In the shell, the statement uses the following form, much like the one used in other languages. if test condition then command(s) else command(s) fi fi is used to indicate the end of the if construct if evaluates a condition which accompanies its command line. If the condition is fulfilled (i.e. returns a true exit status), then the sequence of commands following it is executed. Mark the key words then and fi which must necessarily accompany every if conditional. The construct also provides for an alternate action using the optional keyword else. Note: every if must have an accompanying then and fi, and optionally an else # display the contents of the file page by page echo give the file which u want to see read file lines=`wc -l < $file` echo $file has $lines lines if test $lines -gt 24 then cat $file | less else cat $file fi #Script demonstrating if echo Enter a number read num r=`expr $num % 2` if test $r -eq 0 then echo Number is Even else echo It is Odd fi To test file status using test

www.wilshiresoft.com

Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 53 of 63

Test -f filename Test d filename Test r filename Test w filename Test x filename Test s filename Operator -eq -ne -gt -ge -lt -le

True if file exists and is an ordinary file True if file exists and is a directory True if file exists and is a readable True if file exists and is writeable True if file exists and is executable True if file exists and is not empty Meaning Equal to Not equal to Greater than Greater than or equal Less than Less than or equal to

When you utilize if to evaluate expressions, the test statement is invariably used as its control command. On most UNIX system, it is an internal feature of the shell, test evaluates the condition place on its right, and returns either a true or false exist status. This return value is used by if for taking decisions. #Illustrating test option if test -f abc then echo "File is an ordinary file" else echo "File is not an ordinary file" fi Arithmetic tests and string tests #finding the percentages and grades of the students

echo enter the maths marks read maths echo enter the science marks read science echo enter the social marks read social total=`expr $maths + $science + $social` echo the total of the three subjects is $total percentage=`expr $total / 3` echo the percentage of the subjects is $percentage if test $maths -lt 35 -o $science -lt 35 -o $social -lt 35 then echo student is failed elsewww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 54 of 63

if test $percentage -lt 35 then echo sorry the candidate is failed else if test $percentage -ge 35 -a $percentage -lt 60 then echo congratulations u got "c" grade else if test $percentage -ge 60 -a $percentage -lt 80 then echo congratulations u got "B" grade else echo congratulations u got "A" grade fi fi fi fi

9.12. String test Operators$1 = $2 $1 != $2 -z S1 True if strings S1 and S2 are identical True if strings are not identical True if S1 contains no characters

# SCRIPT TO SEARCH FOR A STRING IN A FILE USING STRING OPERATORS $cat emp.sh echo enter the string to be searched : read pname if [ -z $pname ] then echo you have not entered the string exit 1 fi echo enter the file name to be used: read flname if [ ! n $fname ] then echo you have not entered the file name exit 2 else echo seach for $pname from $fname?: read answer if [ $answer = y ] then grep $fname $flname || echo pattern not found elsewww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 55 of 63

exit 3 fi fi $

9.13. Logical operators-o -a Or And

#Script to find the greatest of twoclear echo "Enter 2 numbers" read a read b if test $a -eq $b then echo "A & B Are equal " elif test $a -gt $b then echo A is greater else echo B is greater fi

9.14. The case...esac constructThe case statement is the second conditional offered by the shell. It doesnt have its parallel in most languages. The statement matches on expression for more than one alternative, and uses a compact construct to permit multi-way branching. It also handles string tests, but in a more efficient manner than if. The general syntax of case statement is as follows: syntax: case $variablename in value1) command command : : ;; value2) command command : : ;; : : esac

case..esac construct evaluates the value of the variable and compares it with each value specified(value1,value2,...) When the value of the variable matches one of the values specified, the set of commands specified under the value is/are executed. The last command to be executed for any value of the variable must be followed by a pair of semicolons. For example using this construct. You can devise a script, which accepts values from 1 to 5, and performs some action depending on the number keyed in. the code for this menu is stored in the file menu.sh :www.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 56 of 63

$ cat menu.sh echo menu 1. list of files 2. process of user 3. todays date 4. users of system 5. quit to system echo Enter your option :\c read choice case $choice in 1) 2) 3) 4) 5) esac The five menu choices are displayed with a multi-line echo statement. The meanings attached to these choices are obvious enough. The user response from the keyboard is accepted to the variable choice. The case statement then matches the value of this variable for the strings 1,2,3,4, and 5, as shown in the five lines below the key word case. It then relates each value to a command that has to be executed. Note : The last case option need not have the ;; though you can provide them if you want. #Script to check if a given character is Vowel or not echo "Enter a character" read a case $a in [aA])echo $a is Vowel;; [eE])echo $a is Vowel;; [iI])echo $a is Vowel;; [oO])echo $a is Vowel;; [uU])echo $a is Vowel;; [0-9]*)echo $a is a number;; *)echo $a is consonant;; esac * is interpreted as any value other than those listed earlier with case ls l ;; ps f ;; date ;; who ;; exit

9.15. for..do..doneThe for loop is different in structure from the ones used in other programming languages. There is no next statement here, neither can a step be specified. Unlike while and until, it doesnt test a condition but uses as list instead. The syntax is as follows: syntax : for variable name in list of values do command command : : done Examplewww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 57 of 63

for x in 1 2 3 4 do echo $x done #Demonstrating a for loop #To rename all .c files to .cpp for fname in *.c do nname=`echo $fname | sed 's/.c$/.cpp/'` mv $fname $nname done

9.16. while..do..doneThe pattern scanning scripts developed so far still suffer from serious defects. You have no way of giving the user another chance when he has made a faulty response. And you are able to scan only one pattern at a time. Loops let you perform a set of instructions repeatedly. The shell features three types of loops while, until and for. The first two are basically complementary to each other. All of them repeat the instruction set enclosed by certain keywords as often as the control command permits. The while statement should be quite familiar to most programmers. It repeatedly performs a set of instructions till the control command returns a true exist status. The general syntax of this command is as follows: while condition do command command : : done # sample script using while loop $ cat menu.sh while : do echo menu 6. list of files 7. process of user 8. todays date 9. users of system 10. quit to system echo Enter your option :\c read choice case $choice in 6) 7) 8) 9) 10) ls l ;; ps f ;; date ;; who ;; exit

esac echo do you want to continue read chc if [ $chc = y o Y ] then continue else break donewww.wilshiresoft.com Wilshire Software Technologies Ph: 2761-2214 / 2760-6414

Key to Unix

Page 58 of 63

#Script to display "Hello" 10 times i=1 while [ $i -le 10 ] do echo Hello i=`expr $i + 1` done #Script demonstrating while true loop while true do clear cat does not exist. This is because I/O redirection and piping is done before variable substitution. So once the variable has been substituted the shell cannot do redirection and thus attempts to cat three files Mayfield, > and yourfile. Hence eval cat $output (c) Consider the following: cat