record unixit

95
1 LAB OBJECTIVE: Upon successful completion of this Lab the student will be able to-- 1. Demonstrate how to use the following Bourne Shell commands: cat, grep, ls, more, ps, chmod, finger, ftp, etc. 2. Use the following Bourne Shell constructs: test, if then, if then else, if then elif, for, while, until, and case. 3. Learn tracing mechanisms (for debugging), user variables, Bourne Shell variables, read-only variables, positional parameters, reading input to a Bourne Shell script, command substitution, comments, and exporting variables. In addition, test on numeric values, test on file type, and test on character strings are covered. 4. Copy, move, and delete files and directories 5. Write moderately complex Shell scripts. 6. Make a Shell script executable. 7. Create a ".profile" script to customize the user environment. 8. Use advanced features of File Transfer Protocol (FTP) 9. Compile source code into object and executable modules. 10. Execute programs written in c under UNIX environment Coastal Institute of Technology and Management

Upload: brushyendra

Post on 16-Nov-2014

55 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Record UnixIT

1

LAB OBJECTIVE:

Upon successful completion of this Lab the student will be able to--

1. Demonstrate how to use the following Bourne Shell commands: cat, grep, ls, more, ps, chmod, finger, ftp, etc.

2. Use the following Bourne Shell constructs: test, if then, if then else, if then elif, for, while, until, and case.

3. Learn tracing mechanisms (for debugging), user variables, Bourne Shell variables, read-only variables, positional parameters, reading input to a Bourne Shell script, command substitution, comments, and exporting variables. In addition, test on numeric values, test on file type, and test on character strings are covered.

4. Copy, move, and delete files and directories

5. Write moderately complex Shell scripts.

6. Make a Shell script executable.

7. Create a ".profile" script to customize the user environment.

8. Use advanced features of File Transfer Protocol (FTP)

9. Compile source code into object and executable modules.

10. Execute programs written in c under UNIX environment

Coastal Institute of Technology and Management

Page 2: Record UnixIT

2

INTRODUCTION ABOUT LAB:

There are 64 systems (HCL) installed in this Lab. Their configurations are as follows

Processor : Intel Pentium Dual Core CPU E2160 1.80GHz

RAM : 1 GB

Hard Disk : 160 GB

Mouse : Optical Mouse

Network Interface card: Present

Software:

All systems are configured in DUAL BOOT mode i.e., Students can boot from Windows XP or Linux as per their lab requirement.

This is very useful for students because they are familiar with different Operating Systems so that they can execute their programs in different programming environments.

Each student has a separate login for database access

Oracle 9i client version is installed in all systems. On the server, account for each student has been created.

This is very useful because students can save their work (scenarios’, pl/sql programs, data related projects, etc) in their own accounts. Each student work is safe and secure from other students.

Latest Technologies like DOT NET and J2EE are installed in some systems. Before submitting their final project, they can start doing mini project from 2nd year onwards.

MASM ( Macro Assembler ) is installed in all the systems

Students can execute their assembly language programs using MASM. MASM is very useful students because when they execute their programs they can see contents of Processor Registers and how each instruction is being executed in the CPU.

Rational Rose Software is installed in some systems

Using this software, students can depict UML diagrams of their projects.

Coastal Institute of Technology and Management

Page 3: Record UnixIT

3

Software’s installed: C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT NET, Rational Rose.

Systems are provided for students in the 1:1 ratio.

Systems are assigned numbers and same system is allotted for students when they do the lab.

How to Run Shell Scripts:

There are two ways you can execute your shell scripts. Once you have created a script file:

Method 1:

Pass the file as an argument to the shell that you want to interpret your script.

Step 1: create the script using vi, ex or ed

For example, the script file show has the following lines

echo Here is the date and time

date

Step 2: To run the script, pass the filename as an argument to the sh (shell )

$ sh show

Here is the date and time

Sat jun 03 13:40:15 PST 2006

Method 2:

Make your script executable using the chmod command.

When we create a file, by default it is created with read and write permission turned on and execute permission turned off. A file can be made executable using chmod.

Step 1: create the script using vi, ex or ed

For example, the script file show has the following lines

echo Here is the date and time

date

Coastal Institute of Technology and Management

Page 4: Record UnixIT

4

Step 2: Make the file executable

$ chmod u+x script_file

$ chmod u+x show

Step 3: To run the script, just type the filename

$ show

Here is the date and time

Sat jun 03 13:40:15 PST 2006

How to run C programs:

Step 1: Use an editor, such as vi, ex, or ed to write the program. The name of the file containing the program should end in .c

For example, the file hello.c contains the following lines:

#include<stdio.h>int main(){

printf(“ Welcome to CITM “);return 0;

}

Step 2: Submit the file to CC (the C Compiler) to compile the program

$ cc –c hello.c If the program is okay, have to create execute file

Step 3: To create execute file, $ cc –o hello hello.o

Step 3: To run the program, type. /hello

$. /helo Welcome to CITM

How to run C++ programs:

Step 1: Use an editor, such as vi, ex, or ed to write the program. The name of the file containing the program should end in .C

Coastal Institute of Technology and Management

Page 5: Record UnixIT

5

For example, the file hello.C contains the following lines:

#include<iostream.h>int main(){

cout<<”\n Welcome to CITM”;return 0;

}

Step 2: Submit the file to CC (the C++ Compiler) to compile the program

$ CC –c hello.C If the program is okay, have to create execute file

Step 3: To create execute file, $ CC –o hello hello.o

Step 3: To run the program, type. /hello

$. /helo Welcome to CITM

How to run java programs:

Step 1: Use an editor, such as vi, ex, or ed to write the program. The name of the file containing the class name of a program

For example, the class test contains the following lines:

Public class test{

Public static void main(string s[]){System.out.println(“Welcome to CITM”);}

}

Step 2: Submit the file to javac ( the JAVA Compiler )

$ javac test.java

Step 3: To run the program, type java test

$ java test

Coastal Institute of Technology and Management

Page 6: Record UnixIT

6

The vi Editor:

To write and edit some programs and scripts, we require editors. UNIX provides vi editor for BSD system – created by Bill Joy. Bram Moolenaar improved vi editor and called it as vim (vi improved) on Linux OS.

vi Basics

To add some text to a file, we invoke,

vi <filename>

In all probability, the file doesn’t exist, and vi presents you a full screen with the filename shown at the bottom with the qualifier. The cursor is positioned at the top and all remaining lines of the screen show a ~. They are non-existent lines. The last line is reserved for commands that you can enter to act on text. This line is also used by the system to display messages. This is the command mode. This is the mode where you can pass commands to act on text, using most of the keys of the keyboard. This is the default mode of the editor where every key pressed is interpreted as a command to run on text. You will have to be in this mode to copy and delete text

For, text editing, vi uses 24 out of 25 lines that are normally available in the terminal. To enter text, you must switch to the input mode. First press the key i, and you are in this mode ready to input text. Subsequent key depressions will then show up on the screen as text input.

After text entry is complete, the cursor is positioned on the last character of the last line. This is known as current line and the character where the cursor is stationed is the current cursor position. This mode is used to handle files and perform substitution. After the command is run, you are back to the default command mode. If a word has been misspelled, use ctrl-w to erase the entire word.

Now press esc key to revert to command mode. Press it again and you will hear a beep. A beep in vi indicates that a key has been pressed unnecessarily. Actually, the text entered has not been saved on disk but exists in some temporary storage called a buffer. To save the entered text, you must switch to the execute mode (the last line mode). Invoke the execute mode from the command mode by entering a: which shows up in the last line.

The Repeat Factor

vi provides repeat factor in command and input mode commands. Command mode command k moves the cursor one line up. 10k moves cursor 10 lines up.

To undo whenever you make a mistake, press

Esc u

To clear the screen in command mode, press

ctrl-l

Don’t use (caps lock) - vi commands are case-sensitive

Coastal Institute of Technology and Management

Page 7: Record UnixIT

7

Avoid using the PC navigation keys

Input Mode – Entering and Replacing Text

It is possible to display the mode in which is user is in by typing,

:set showmode

Messages like INSERT MODE, REPLACE MODE, CHANGE MODE, etc will appear in the last line.

Pressing ‘i’ changes the mode from command to input mode. To append text to the right of the cursor position, we use a, text. I and A behave same as i and a, but at line extremes

I inserts text at the beginning of line. A appends text at end of line. o opens a new line below the current line

• r<letter> replacing a single character• s<text/word> replacing text with s• R<text/word> replacing text with R• Press esc key to switch to command mode after you have keyed in text

Some of the input mode commands are:

COMMAND FUNCTION

i inserts text

a appends text

I inserts at beginning of line

A appends text at end of line

o opens line below

O opens line above

r replaces a single character

s replaces with a text

S replaces entire line

Saving Text and Quitting – The ex Mode

When you edit a file using vi, the original file is not distributed as such, but only a copy of it that is placed in a buffer. From time to time, you should save your work by writing the buffer contents to disk to keep the disk file current. When we talk of saving a file, we actually mean saving this buffer. You may also need to quit vi after or without saving the buffer. Some of the save and exit commands of the ex mode is:

Command Action

Coastal Institute of Technology and Management

Page 8: Record UnixIT

8

:W saves file and remains in editing mode

:x saves and quits editing mode

:wq saves and quits editing mode

:w <filename> save as

:w! <filename> save as, but overwrites existing file

:q quits editing mode

:q! quits editing mode by rejecting changes made

:sh escapes to UNIX shell

:recover recovers file from a crash

Navigation

A command mode command doesn’t show up on screen but simply performs a function.

To move the cursor in four directions,

k moves cursor up

j moves cursor down

h moves cursor left

l moves cursor right

Word Navigation

Moving by one character is not always enough. You will often need to move faster along a line. vi understands a word as a navigation unit which can be defined in two ways, depending on the key pressed. If your cursor is a number of words away from your desired position, you can use the word-navigation commands to go there directly. There are three basic commands:

b moves back to beginning of word

e moves forward to end of word

w moves forward to beginning word

Example,

5b takes the cursor 5 words back

3w takes the cursor 3 words forward

Coastal Institute of Technology and Management

Page 9: Record UnixIT

9

Moving to Line Extremes

Moving to the beginning or end of a line is a common requirement.

To move to the first character of a line 0 or |

30| moves cursor to column 30

$ moves to the end of the current line

The use of these commands along with b, e, and w is allowed

Scrolling

Faster movement can be achieved by scrolling text in the window using the control keys. The two commands for scrolling a page at a time are

ctrl-f scrolls forward

ctrl-b scrolls backward

10ctrl-f scroll 10 pages and navigate faster

ctrl-d scrolls half page forward

ctrl-u scrolls half page backward

Absolute Movement

The editor displays the total number of lines in the last line

Ctrl-g to know the current line number

40G goes to line number 40

1G goes to line number 1

G goes to end of file

Editing Text

The editing facilitates in vi are very elaborate and invoke the use of operators. They use operators, such as,

d delete

y yank (copy)

Deleting Text

x deletes a single character

dd delete entire line

yy copy entire line

Coastal Institute of Technology and Management

Page 10: Record UnixIT

10

6dd deletes the current line and five lines below

Moving Text

Moving text (p) puts the text at the new location.

p and P place text on right and left only when you delete parts of lines. But the same keys get associated with “below” and “above” when you delete complete lines

Copying Text

Copying text (y and p) is achieved as,

yy copies current line

10yy copies current line & 9 lines below

Joining Lines

J to join the current line and the line following it

4J joins following 3 lines with current line

Undoing Last Editing Instructions

In command mode, to undo the last change made, we use u

To discard all changes made to the current line, we use U

vim (LINUX) lets you undo and redo multiple editing instructions. u behaves differently here; repeated use of this key progressively undoes your previous actions. You could even have the original file in front of you. Further 10u reverses your last 10 editing actions. The function of U remains the same.

You may overshoot the desired mark when you keep u pressed, in which case use ctrl-r to redo your undone actions. Further, undoing with 10u can be completely reversed with 10ctrl-r. The undoing limit is set by the execute mode command: set undolevels=n, where n is set to 1000 by default.

Repeating the Last Command

The. (dot) command is used for repeating the last instruction in both editing and command mode commands

For example:

2dd deletes 2 lines from current line and to repeat this operation, type. (dot)

Coastal Institute of Technology and Management

Page 11: Record UnixIT

11

Searching for a Pattern

/ search forward

? search backward

/printf

The search begins forward to position the cursor on the first instance of the word

?pattern

Searches backward for the most previous instance of the pattern

Repeating the Last Pattern Search

N repeats search in same direction of original search

n doesn’t necessarily repeat a search in the forward direction. The direction depends on the search command used. If you used? printf to search in the reverse direction in the first place, then n also follows the same direction. In that case, N will repeat the search in the forward direction, and not n.

Search and repeat commands

Command Function

/pat searches forward for pattern pat

?pat searches backward for pattern pat

n repeats search in same direction along which previous search was made

N repeats search in direction opposite to that along which previous search was made

Substitution – search and replace

We can perform search and replace in execute mode using: s. Its syntax is,

:address/source_pattern/target_pattern/flags

:1,$s/director/member/g can also use % instead of 1,$

:1,50s/unsigned//g deletes unsigned everywhere in lines 1 to 50

:3,10s/director/member/g substitute lines 3 through 10

:.s/director/member/g only the current line

:$s/director/member/g only the last line

Interactive substitution: sometimes you may like to selectively replace a string. In that case, add the c parameter as the flag at the end:

:1,$s/director/member/gc

Coastal Institute of Technology and Management

Page 12: Record UnixIT

12

Each line is selected in turn, followed by a sequence of carets in the next line, just below the pattern that requires substitution. The cursor is positioned at the end of this caret sequence, waiting for your response.

The ex mode is also used for substitution. Both search and replace operations also use regular expressions for matching multiple patterns.

The features of vi editor that have been highlighted so far are good enough for a beginner who should not proceed any further before mastering most of them. There are many more functions that make vi a very powerful editor. Can you copy three words or even the entire file using simple keystrokes? Can you copy or move multiple sections of text from one file to another in a single file switch? How do you compile your C and Java programs without leaving the editor? vi can do all this.

System Calls:

System calls are special set of functions available in several programming languages. They are used by programs to communicate directly with an operating system. The operating system communicates back to the user's program through the return value of the function.

Generally, system calls are slower than normal function calls. The reason is because when you call a system call, control is relinquished to the operating system to perform the system call. In addition, depending on the nature of the system call, your program may be blocked by the OS until the system call has finished, thus making the execution time of your program even longer.

One rule of thumb should always be followed when calling a system call: Always check the return value. The return value is the only method that the operating system has to communicate information to your program. Thus, you should always check the return value in the event that the system call failed.

List of C System Calls

close

dup

dup2

festal

lseek

lstat

open

Coastal Institute of Technology and Management

Page 13: Record UnixIT

13

read

stat

write

open (C System Call)

open is a system call that is used to open a new file and obtain its file descriptor.

Required Include Files

#include <fcntl.h>

/* Not technically required, but needed on some UNIX distributions */

#include <sys/types.h>

#include <sys/stat.h>

Function Definition

int open(const char *path, int oflags);

int open(const char *path, int oflags, mode_t mode);

Field Description

const char *path

The relative or absolute path to the file that is to be opened.

int oflagsA bitwise 'or' separated list of values that determine the method in which the file is to be opened (whether it should be read only, read/write, whether it should be cleared when opened, etc). See a list of legal values for this field at the end.

mode_t mode

A bitwise 'or' separated list of values that determine the permissions of the file if it is created. See a list of legal values at the end.

return value

Returns the file descriptor for the new file. The file descriptor returned is always the smallest integer greater than zero that is still available. If a negative value is returned, then there was an error opening the file.

Example

Example using the open system call:

#include <unistd.h>

#include <fcntl.h>

Coastal Institute of Technology and Management

Page 14: Record UnixIT

14

int main()

{

size_t filedesc = open("testfile.txt", O_WRONLY | O_APPEND);

if(filedesc < 0)

return 1;

if(write(filedesc,"This will be output to testfile.txt\n", 36) != 36)

{

write(2,"There was an error writing to testfile.txt\n",43);

return 1;

}

return 0;

}

Available Values for oflag

Value Meaning

O_RDONLY Open the file so that it is read only.

O_WRONLY Open the file so that it is write only.

O_RDWR Open the file so that it can be read from and written to.

O_APPEND Append new information to the end of the file.

O_TRUNC Initially clear all data from the file.

O_CREATIf the file does not exist, create it. If the O_CREAT option is used, then you must include the third parameter.

O_EXCLCombined with the O_CREAT option, it ensures that the caller must create the file. If the file already exists, the call will fail.

Coastal Institute of Technology and Management

Page 15: Record UnixIT

15

Available Values for mode

Value Meaning

S_IRUSR Set read rights for the owner to true.

S_IWUSR Set write rights for the owner to true.

S_IXUSR Set execution rights for the owner to true.

S_IRGRP Set read rights for the group to true.

S_IWGRP Set write rights for the group to true.

S_IXGRP Set execution rights for the group to true.

S_IROTH Set read rights for other users to true.

S_IWOTH Set write rights for other users to true.

S_IXOTHSet execution rights for other users to true.

close (C System Call)

close is a system call that is used to close an open file descriptor.

Required Include Files

#include <unistd.h>

Function Definition

int close(int fieldes);

Field Description

int fieldes

The file descriptor to be closed.

return value

Retuns a 0 upon success, and a -1 upon failure. It is important to check the return value, because some network errors are not returned until the file is closed.

Coastal Institute of Technology and Management

Page 16: Record UnixIT

16

Example

Example closing an open file descriptor:

#include <stdlib.h>

#include <fcntl.h>

int main()

{

size_t filedesc = open("testfile.txt", O_WRONLY | O_CREAT);

if(filedesc < 0)

return 1;

if(close(filedesc) < 0)

return 1;}return 0;}

read (C System Call)

read is a system call used to read data into a buffer.

Required Include Files

#include <unistd.h>

Function Definition

size_t read(int fildes, void *buf, size_t nbytes);

Field Description

int fildesThe file descriptor of where to write the output. You can either use a file descriptor obtained from the open system call, or you can use 0, 1, or 2, to refer to standard input, standard output, or standard error, respectively.

const void *buf

A character array where the read content will be stored.

size_t nbytes

The number of bytes to read before truncating the data. If the data to be read is smaller than nbytes, all data is saved in the buffer.

return value

Returns the number of bytes that were read. If value is negative, then the system call returned an error.

Coastal Institute of Technology and Management

Page 17: Record UnixIT

17

Example

#include <unistd.h>

int main()

{

char data[128];

if(read(0, data, 128) < 0)

write(2, "An error occurred in the read.\n", 31);

exit(0);

}

write (C System Call)

write is a system call that is used to write data out of a buffer.

Required Include Files

#include <unistd.h>

Function Definition

size_t write(int fildes, const void *buf, size_t nbytes);

Field Description

int fildesThe file descriptor of where to write the output. You can either use a file descriptor obtained from the open system call, or you can use 0, 1, or 2, to refer to standard input, standard output, or standard error, respectively.

const void *buf

A null terminated character string of the content to write.

size_t nbytes

The number of bytes to write. If smaller than the provided buffer, the output is truncated.

return value

Returns the number of bytes that were written. If value is negative, then the system call returned an error.

Coastal Institute of Technology and Management

Page 18: Record UnixIT

18

Example

Example using standard file descriptors:

#include <unistd.h>

int main()

{

if(write(1,"This will be output to standard out\n", 36) != 36)

{

write(2,"There was an error writing to standard out\n",44);

return 1;

}

return 0;

}

Example using a file descriptor:

#include <unistd.h>

#include <fcntl.h>

int main()

{

size_t filedesc = open("testfile.txt", O_WRONLY | O_APPEND);

if(filedesc < 0)

return 1;

if(write(filedesc,"This will be output to testfile.txt\n", 36) != 36)

{

write(2,"There was an error writing to testfile.txt\n",43);

return 1;

}

return 0;

}

Coastal Institute of Technology and Management

Page 19: Record UnixIT

19

stat (C System Call)

stat is a system call that is used to determine information about a file based on its file path.

Required Include Files

#include <unistd.h>

#include <sys/stat.h>

#include <sys/types.h>

Function Definition

int stat(const char *path, struct stat *buf);

Field Description

const char *path

The file descriptor of the file that is being inquired.

struct stat *buf

A structure where data about the file will be stored. A detailed look at all of the fields in this structure can be found in the struct stat page.

return value

Returns a negative value on failure.

Example

An example of code that uses the stat() system call is below.

#include <unistd.h>

#include <stdio.h>

#include <sys/stat.h>

#include <sys/types.h>

int main(int argc, char **argv)

{

if(argc != 2)

return 1;

struct stat fileStat;

if(stat(argv[1],&fileStat) < 0)

Coastal Institute of Technology and Management

Page 20: Record UnixIT

20

return 1;

printf("Information for %s\n",argv[1]);

printf("---------------------------\n");

printf("File Size: \t\t%d bytes\n",fileStat.st_size);

printf("Number of Links: \t%d\n",fileStat.st_nlink);

printf("File inode: \t\t%d\n",fileStat.st_ino);

printf("File Permissions: \t");

printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");

printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");

printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");

printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");

printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");

printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");

printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");

printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");

printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");

printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");

printf("\n\n");

printf("The file %s a symbolic link\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");

return 0;

}

The output of this program is shown in the following set of commands:

Information on the current files in the directory:

$ ls -l

total 16

-rwxr-xr-x 1 stargazer stargazer 36 2009-05-06 20:50 testfile.sh

-rwxr-xr-x 1 stargazer stargazer 7780 2009-05-07 12:36 testProgram

-rw-r--r-- 1 stargazer stargazer 1229 2009-05-07 12:04 testProgram.c

Coastal Institute of Technology and Management

Page 21: Record UnixIT

21

Running the program with the file testfile.sh

$ ./testProgram testfile.sh

Information for testfile.sh

---------------------------

File Size: 36 bytes

Number of Links: 1

File inode: 180055

File Permissions: -rwxr-xr-x

The file is not a symbolic link

Running the program with the files testProgram.c

$ ./testProgram testProgram.c

Information for testProgram.c

---------------------------

File Size: 1229 bytes

Number of Links: 1

File inode: 295487

File Permissions: -rw-r--r--

The file is not a symbolic link

Running the program with the directory /home/stargazer

$ ./testProgram /home/stargazer

Information for /home/stargazer

---------------------------

File Size: 4096 bytes

Number of Links: 61

File inode: 32706

File Permissions: drwxr-xr-x

The file is not a symbolic link

fstat (C System Call)

Coastal Institute of Technology and Management

Page 22: Record UnixIT

22

fstat is a system call that is used to determine information about a file based on its file descriptor.

Required Include Files

#include <unistd.h>

#include <sys/stat.h>

#include <sys/types.h>

Function Definition

int fstat(int fildes, struct stat *buf);

Field Description

int fildes The file descriptor of the file that is being inquired.

struct stat *buf A structure where data about the file will be stored.

return value Returns a negative value on failure.

Example

An example of code that uses the fstat() system call is below.

#include <unistd.h>

#include <fcntl.h>

#include <stdio.h>

#include <sys/stat.h>

#include <sys/types.h>

int main(int argc, char **argv)

{

if(argc != 2)

return 1;

int file=0;

if((file=open(argv[1],O_RDONLY)) < -1)

return 1;

Coastal Institute of Technology and Management

Page 23: Record UnixIT

23

struct stat fileStat;

if(fstat(file,&fileStat) < 0)

return 1;

printf("Information for %s\n",argv[1]);

printf("---------------------------\n");

printf("File Size: \t\t%d bytes\n",fileStat.st_size);

printf("Number of Links: \t%d\n",fileStat.st_nlink);

printf("File inode: \t\t%d\n",fileStat.st_ino);

printf("File Permissions: \t");

printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");

printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");

printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");

printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");

printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");

printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");

printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");

printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");

printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");

printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");

printf("\n\n");

printf("The file %s a symbolic link\n\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");

return 0;

}

The output of this program is shown in the following set of commands:

Information on the current files in the directory:

$ ls -l

total 16

-rwxr-xr-x 1 stargazer stargazer 36 2009-05-06 20:50 testfile.sh

Coastal Institute of Technology and Management

Page 24: Record UnixIT

24

-rwxr-xr-x 1 stargazer stargazer 7780 2009-05-07 12:36 testProgram

-rw-r--r-- 1 stargazer stargazer 1229 2009-05-07 12:04 testProgram.c

Running the program with the file testfile.sh

$ ./testProgram testfile.sh

Information for testfile.sh

---------------------------

File Size: 36 bytes

Number of Links: 1

File inode: 180055

File Permissions: -rwxr-xr-x

The file is not a symbolic link

Running the program with the files testProgram.c

$ ./testProgram testProgram.c

Information for testProgram.c

---------------------------

File Size: 1229 bytes

Number of Links: 1

File inode: 295487

File Permissions: -rw-r--r--

The file is not a symbolic link

Running the program with the directory /home/stargazer

$ ./testProgram /home/stargazer

Information for /home/stargazer

---------------------------

File Size: 4096 bytes

Number of Links: 61

File inode: 32706

File Permissions: drwxr-xr-x

Coastal Institute of Technology and Management

Page 25: Record UnixIT

25

The file is not a symbolic link

lstat (C System Call)

lstat is a system call that is used to determine information about a file based on its filename.

lstat is exactly the same as the stat system call. The only difference between the two is when the filename refers to a link. When this is the case, lstat returns information about the link itself, whereas stat returns information about the actual file.

Required Include Files

#include <unistd.h>

#include <sys/stat.h>

#include <sys/types.h>

Function Definition

int lstat(const char *path, struct stat *buf);

Field Description

const char *path

The file path of the file that is being inquired. This can be both relative and absolute.

struct stat *buf A structure where data about the file will be stored.

return value Returns a negative value on failure.

Example

The code for using lstat is exactly the same as the code for using stat. As mentioned before, the only difference between the two functions is when the target is a symbolic link.

lseek (C System Call)

lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.

Required Include Files

#include <unistd.h>

#include <sys/types.h>

Function Definition

off_t lseek(int fildes, off_t offset, int whence);

Coastal Institute of Technology and Management

Page 26: Record UnixIT

26

Field Description

int fildes The file descriptor of the pointer that is going to be moved.

off_t offset

The offset of the pointer (measured in bytes).

int whence

The method in which the offset is to be interpreted (relative, absolute, etc.). Legal values for this variable are provided at the end.

return value

Returns the offset of the pointer (in bytes) from the beginning of the file. If the return value is -1, then there was an error moving the pointer.

Example

The following is an example using the lseek system call.

#include <unistd.h>

#include <fcntl.h>

#include <sys/types.h>

int main()

{

int file=0;

if((file=open("testfile.txt",O_RDONLY)) < -1)

return 1;

char buffer[19];

if(read(file,buffer,19) != 19) return 1;

printf("%s\n",buffer);

if(lseek(file,10,SEEK_SET) < 0) return 1;

if(read(file,buffer,19) != 19) return 1;

printf("%s\n",buffer); return 0;

}

The output of the preceding code is:

$ cat testfile.txt

Coastal Institute of Technology and Management

Page 27: Record UnixIT

27

This is a test file that will be used to demonstrate the use of lseek.

$ ./testing

This is a test file

test file that will

Available Values for whence

Value Meaning

SEEK_SET Offset is to be measured in absolute terms.

SEEK_CUR Offset is to be measured relative to the current location of the pointer.

SEEK_END Offset is to be measured relative to the end of the file.

dup (C System Call)

dup is a system call similar to dup2 in that it creates an alias for the provided file descriptor. dup always uses the smallest available file descriptor. Thus, if we called dup first thing in our program, then you could write to standard output by using file descriptor 3 (dup uses 3 because 0, 1, and 2 are already taken by default). You can determine the value of the new file descriptor by saving the return value from dup

Required Include Files

#include <unistd.h>

Function Definition

int dup(int fildes);

Field Description

int fildes The file descriptor that you are attempting to create an alias for.

return value

dup returns the value of the new file descriptor that it has created (which will always be the smallest available file descriptor). A negative return value means that an error occured.

Example

Using dup(), we can create an alias for standard output, as follows:

#include <unistd.h>

int main()

Coastal Institute of Technology and Management

Page 28: Record UnixIT

28

{

int outputAlias = dup(1);

if(write(outputAlias, "This will print to the screen.") < 0)

return 1;

return 0;

}

You can also use dup() to redirect standard output by taking advantage of the fact that it always uses the smallest available file descriptor:

#include <unistd.h>

int main()

{

int file = open("MyFile.txt",O_RDWR);

if( file < 0) return 1;

/* yes, we are about to close standard output */

close(1);

/* Now we call dup to create a duplicate file descriptor. Because dup always

uses the smallest available file descriptor and we just closed file descriptor

1, the return value on dup will be 1. */

if(dup(file) != 1) return 1;

/* We don't need our original file descriptor, because now the file descriptor 1

points to our file. */

close(file);

/* Now all of standard output has been redirected to our file */

printf("This will be printed to MyFile.txt");

return 0;

}

dup2 (C System Call) :dup2 is a system call similar to dup in that it duplicates one file descriptor, making them aliases, and then deleting the old file descriptor. This becomes very useful when attempting to redirect output, as it automatically takes care of closing the old file descriptor, performing the redirection in one elegant command. For example, if you wanted to

Coastal Institute of Technology and Management

Page 29: Record UnixIT

29

redirect standard output to a file, then you would simply call dup2, providing the open file descriptor for the file as the first command and 1 (standard output) as the second command.

Required Include Files

#include <unistd.h>

Function Definition

int dup2(int fildes, int fildes2);

Field Description

int fildes The file descriptor that will be changed.

int fildes2 The file descriptor that will be used to make the copy.

return valuedup2 returns the value of the first parameter (fildes) upon success. A negative return value means that an error occured.

Example

Using dup2(), we can redirect standard output to a file, as follows:

#include <iostream>

#include <unistd.h>

#include <fcntl.h>

using namespace std;

int main()

{

//First, we're going to open a file

int file = open("myfile.txt", O_APPEND | O_WRONLY);

if(file < 0) return 1;

//Now we redirect standard output to the file using dup2

if(dup2(file,1) < 0) return 1;

//Now standard out has been redirected, we can write to

cout << "This will print in myfile.txt" << endl;

return 0; }//end of function main

Coastal Institute of Technology and Management

Page 30: Record UnixIT

30

Why Use Shells? Well, most likely because the are a simple way to string together a bunch of UNIX commands for execution at any time without the need for prior compilation. Also because its generally fast to get a script going. Not forgetting the ease with which other scripters can read the code and understand what is happening. Lastly, they are generally completely portable across the whole UNIX world, as long as they have been written to a common standard.

The Shell History: The basic shells come in three main language forms. These are (in order of creation) sh, csh and ksh. Be aware that there are several dialects of these script languages which tend to make them all slightly platform specific. Where these differences are known to cause difficulties I have made special notes within the text to highlight this fact. The different dialects are due, in the main, to the different UNIX flavours in use on some platforms. All script languages though have at their heart a common core which if used correctly will guarantee portability.

Bourne Shell:Historically the sh language was the first to be created and goes under the name of The Bourne Shell. It has a very compact syntax which makes it obtuse for novice users but very efficient when used by experts. It also contains some powerful constructs built in. On UNIX systems, most of the scripts used to start and configure the operating system are written in the Bourne shell. It has been around for so long that is it virtually bug free. I have adopted the Bourne shell syntax as the defacto standard within this book.

C Shell:Next up was The C Shell (csh), so called because of the similar syntactical structures to the C language. The UNIX man pages contain almost twice as much information for the C Shell as the pages for the Bourne shell, leading most users to believe that it is twice as good. This is a shame because there are several compromises within the C Shell which makes using the language for serious work difficult (check the list of bugs at the end of the man pages!). True, there are so many functions available within the C Shell that if one should fail another could be found. The point is do you really want to spend your time finding all the alternative ways of doing the same thing just to keep yourself out of trouble. The features that guarantee its continued use in this arena are aliases, and history lists. There are rumors however; that C Shell is destined to be phased out, with future UNIX releases only supporting sh and ksh. Differences between csh and sh syntax will be highlighted where appropriate.

Korne Shell:Lastly we come to The Korne Shell (ksh) made famous by IBM's AIX flavour of UNIX. The Korne shell can be thought of as a superset of the Bourne shell as it contains the whole of the Bourne shell world within its own syntax rules. The extensions over and above the Bourne shell exceed even the level of functionality available within the C Shell (but without any of the compromises!), making it the obvious language of choice for real scripters. However, because not all platforms are yet supporting the Korne shell it is not fully portable as a scripting language at the time of writing. This may change however by the time this book is published. Korne Shell does contain aliases and history lists aplenty but C Shell users are often put off by its dissimilar syntax. Persevere, it will pay off eventually. Any sh syntax element will work in the ksh without change

Coastal Institute of Technology and Management

Page 31: Record UnixIT

31

FILTERS USING REGULAR EXPRESSIONS – grep and sed:

We often need to search a file for a pattern, either to see the lines containing (or not containing) it or to have it replaced with something else. This chapter discusses two important filters that are specially suited for these tasks – grep and sed. grep takes care of all search requirements we may have. sed goes further and can even manipulate the individual characters in a line. In fact sed can de several things, some of then quite well.

grep – searching for a pattern

It scans the file / input for a pattern and displays lines containing the pattern, the line numbers or filenames where the pattern occurs. It’s a command from a special family in UNIX for handling search requirements.

grep options pattern filename(s)

grep “sales” emp.lst

will display lines containing sales from the file emp.lst. Patterns with and without quotes is possible. It’s generally safe to quote the pattern. Quote is mandatory when pattern involves more than one word. It returns the prompt in case the pattern can’t be located.

grep president emp.lst

When grep is used with multiple filenames, it displays the filenames along with the output.

grep “director” emp1.lst emp2.lst

Where it shows filename followed by the contents

grep options

grep is one of the most important UNIX commands, and we must know the options that POSIX requires grep to support. Linux supports all of these options.

-i ignores case for matching

-v doesn’t display lines matching expression

-n displays line numbers along with lines

-c displays count of number of occurrences

-l displays list of filenames only

-e exp specifies expression with this option

-x matches pattern with entire line

-f file takes pattrens from file, one per line

-E treats pattren as an extended RE

Coastal Institute of Technology and Management

Page 32: Record UnixIT

32

-F matches multiple fixed strings

grep -i ‘agarwal’ emp.lst

grep -v ‘director’ emp.lst > otherlist

wc -l otherlist will display 11 otherlist

grep –n ‘marketing’ emp.lst

grep –c ‘director’ emp.lst

grep –c ‘director’ emp*.lst

will print filenames prefixed to the line count

grep –l ‘manager’ *.lst

will display filenames only

grep –e ‘Agarwal’ –e ‘aggarwal’ –e ‘agrawal’ emp.lst

will print matching multiple patterns

grep –f pattern.lst emp.lst

all the above three patterns are stored in a separate file pattern.lst

Basic Regular Expressions (BRE) – An Introduction

It is tedious to specify each pattern separately with the -e option. grep uses an expression of a different type to match a group of similar patterns. If an expression uses meta characters, it is termed a regular expression. Some of the characters used by regular expression are also meaningful to the shell.

BRE character subset

The basic regular expression character subset uses an elaborate meta character set, overshadowing the shell’s wild-cards, and can perform amazing matches.

* Zero or more occurrences

g* nothing or g, gg, ggg, etc.

. A single character

.* nothing or any number of characters

[pqr] a single character p, q or r

[c1-c2] a single character within the ASCII range represented by c1 and c2

Coastal Institute of Technology and Management

Page 33: Record UnixIT

33

The character class

grep supports basic regular expressions (BRE) by default and extended regular expressions (ERE) with the –E option. A regular expression allows a group of characters enclosed within a pair of [ ], in which the match is performed for a single character in the group.

grep “[aA]g[ar][ar]wal” emp.lst

A single pattern has matched two similar strings. The pattern [a-zA-Z0-9] matches a single alphanumeric character. When we use range, make sure that the character on the left of the hyphen has a lower ASCII value than the one on the right. Negating a class (^) (caret) can be used to negate the character class. When the character class begins with this character, all characters other than the ones grouped in the class are matched.

The *

The asterisk refers to the immediately preceding character. * indicates zero or more occurrences of the previous character.

g* nothing or g, gg, ggg, etc.

grep “[aA]gg*[ar][ar]wal” emp.lst

Notice that we don’t require to use –e option three times to get the same output!!!!!

The dot

A dot matches a single character. The shell uses ? Character to indicate that.

.* signifies any number of characters or none

grep “j.*saxena” emp.lst

Specifying Pattern Locations (^ and $)

Most of the regular expression characters are used for matching patterns, but there are two that can match a pattern at the beginning or end of a line. Anchoring a pattern is often necessary when it can occur in more than one place in a line, and we are interested in its occurance only at a particular location.

^ for matching at the beginning of a line

$ for matching at the end of a line

grep “^2” emp.lst

Selects lines where emp_id starting with 2

grep “7…$” emp.lst

Selects lines where emp_salary ranges between 7000 to 7999

Coastal Institute of Technology and Management

Page 34: Record UnixIT

34

grep “^[^2]” emp.lst

Selects lines where emp_id doesn’t start with 2

When meta characters lose their meaning

It is possible that some of these special characters actually exist as part of the text. Sometimes, we need to escape these characters. For example, when looking for a pattern g*, we have to use \

To look for [, we use \[

To look for .*, we use \.\*

Extended Regular Expression (ERE) and grep

If current version of grep doesn’t support ERE, then use egrep but without the –E option. -E option treats pattern as an ERE.

+ matches one or more occurrences of the previous character

? Matches zero or one occurrence of the previous character

b+ matches b, bb, bbb, etc.

b? matches either a single instance of b or nothing

These characters restrict the scope of match as compared to the *

grep –E “[aA]gg?arwal” emp.lst

# ?include +<stdio.h>

The ERE set

ch+ matches one or more occurrences of character ch

ch? Matches zero or one occurrence of character ch

exp1|exp2 matches exp1 or exp2

(x1|x2)x3 matches x1x3 or x2x3

Matching multiple patterns (|, ( and ))

grep –E ‘sengupta|dasgupta’ emp.lst

We can locate both without using –e option twice, or

grep –E ‘(sen|das)gupta’ emp.lst

Coastal Institute of Technology and Management

Page 35: Record UnixIT

35

sed – The Stream Editor

sed is a multipurpose tool which combines the work of several filters. sed uses instructions to act on text. An instruction combines an address for selecting lines, with an action to be taken on them.

sed options ‘address action’ file(s)

sed supports only the BRE set. Address specifies either one line number to select a single line or a set of two lines, to select a group of contiguous lines. action specifies print, insert, delete, substitute the text.

sed processes several instructions in a sequential manner. Each instruction operates on the output of the previous instruction. In this context, two options are relevant, and probably they are the only ones we will use with sed – the –e option that lets us use multiple instructions, and the –f option to take instructions from a file. Both options are used by grep in identical manner.

Line Addressing

sed ‘3q’ emp.lst

Just similar to head –n 3 emp.lst. Selects first three lines and quits

sed –n ‘1,2p’ emp.lst

p prints selected lines as well as all lines. To suppress this behavior, we use –n whenever we use p command

sed –n ‘$p’ emp.lst

Selects last line of the file

sed –n ‘9,11p’ emp.lst

Selecting lines from anywhere of the file, between lines from 9 to 11

sed –n ‘1,2p

7,9p

$p’ emp.lst

Selecting multiple groups of lines

sed –n ‘3,$!p’ emp.lst

Negating the action, just same as 1,2p

Using Multiple Instructions (-e and –f)

There is adequate scope of using the –e and –f options whenever sed is used with multiple instructions.

sed –n –e ‘1,2p’ –e ‘7,9p’ –e ‘$p’ emp.lst

Coastal Institute of Technology and Management

Page 36: Record UnixIT

36

Let us consider,

cat instr.fil

1,2p

7,9p

$p

-f option to direct the sed to take its instructions from the file

sed –n –f instr.fil emp.lst

We can combine and use –e and –f options as many times as we want

sed –n –f instr.fil1 –f instr.fil2 emp.lst

sed –n –e ‘/saxena/p’ –f instr.fil1 –f instr.fil2 emp.lst

Context Addressing

We can specify one or more patterns to locate lines

sed –n ‘/director/p’ emp.lst

We can also specify a comma-separated pair of context addresses to select a group of lines.

sed –n ‘/dasgupta/,/saxena/p’ emp.lst

Line and context addresses can also be mixed

sed –n ‘1,/dasgupta/p’ emp.lst

Using regular expressions

Context addresses also uses regular expressions.

Sed –n ‘/[aA]gg*[ar][ar]wal/p’ emp.lst

Selects all agarwals.

Sed –n ‘/sa[kx]s*ena/p

/gupta/p’ emp.lst

Selects saxenas and gupta.

We can also use ^ and $, as part of the regular expression syntax.

sed –n ‘/50…..$/p’ emp.lst

Selects all people born in the year 1950.

Coastal Institute of Technology and Management

Page 37: Record UnixIT

37

Writing Selected Lines to a File (w)

We can use w command to write the selected lines to a separate file.

sed –n ‘/director/w dlist’ emp.lst

Saves the lines of directors in dlist file

sed –n ‘/director/w dlist

/manager/w mlist

/executive/w elist’ emp.lst

Splits the file among three files

sed –n ‘1,500w foo1

501,$w foo2’ foo.main

Line addressing also is possible. Saves first 500 lines in foo1 and the rest in foo2

Text Editing

sed supports inserting (i), appending (a), changing (c) and deleting (d) commands for the text.

$ sed ‘1i\

> #include <stdio.h>\

> #include <unistd.h>

> ’foo.c > $$

Will add two include lines in the beginning of foo.c file. Sed identifies the line without the \ as the last line of input. Redirected to $$ temporary file. This technique has to be followed when using the a and c commands also. To insert a blank line after each line of the file is printed (double spacing text), we have,

sed ‘a\

’ emp.lst

Deleting lines (d)

sed ‘/director/d’ emp.lst > olist or

sed –n ‘/director/!p’ emp.lst > olist

Selects all lines except those containing director, and saves them in olist

Note that –n option not to be used with d

Coastal Institute of Technology and Management

Page 38: Record UnixIT

38

Substitution (s)

Substitution is the most important feature of sed, and this is one job that sed does exceedingly well.

[address]s/expression1/expression2/flags

Just similar to the syntax of substitution in vi editor, we use it in sed also.

sed ‘s/|/:/’ emp.lst | head –n 2

2233:a.k.shukla |gm |sales |12/12/52|6000

9876:jai sharma |director|production|12/03/50|7000

Only the first instance of | in a line has been replaced. We need to use the g (global) flag to replace all the pipes

sed ‘s/|/:/g’ emp.lst | head –n 2

We can limit the vertical boundaries too by specifying an address (for first three lines only).

sed ‘1,3s/|/:/g’ emp.lst

Replace the word director with member in the first five lines of emp.lst

sed ‘1,5s/director/member/’ emp.lst

sed also uses regular expressions for patterns to be substituted. To replace all occurrence of agarwal, aggarwal and agrawal with simply Agarwal, we have,

sed ‘s/[Aa]gg*[ar][ar]wal/Agarwal/g’ emp.lst

We can also use ^ and $ with the same meaning. To add 2 prefix to all emp-ids,

sed ‘s/^/2/’ emp.lst | head –n 1

22233 | a.k.shukla | gm | sales | 12/12/52 | 6000

To add .00 suffix to all salary,

sed ‘s/$/.00/’ emp.lst | head –n 1

2233 | a.k.shukla | gm | sales | 12/12/52 | 6000.00

Performing multiple substitutions

sed ‘s/<I>/<EM>/g

s/<B>/<STRONG>/g

s/<U>/<EM>/g’ form.html

An instruction processes the output of the previous instruction, as sed is a stream editor and works on data stream

Coastal Institute of Technology and Management

Page 39: Record UnixIT

39

sed ‘s/<I>/<EM>/g

s/<EM>/<STRONG>/g’ form.html

When a ‘g’ is used at the end of a substitution instruction, the change is performed globally along the line. Without it, only the left most occurrence is replaced. When there are a group of instructions to execute, you should place these instructions in a file instead and use sed with the –f option.

Compressing multiple spaces

sed ‘s/*|/|/g’ emp.lst | tee empn.lst | head –n 3

2233|a.k.shukla|g.m|sales|12/12/52|6000

9876|jai sharma|director|production|12/03/50|7000

5678|sumit chakrobarty|dgm|mrking|19/04/43|6000

The remembered patterns

Consider the below three lines which does the same job

sed ‘s/director/member/’ emp.lst

sed ‘/director/s//member/’ emp.lst

sed ‘/director/s/director/member/’ emp.lst

The // representing an empty regular expression is interpreted to mean that the search and substituted patterns are the same

sed ‘s/|//g’ emp.lst removes every | from file

Basic Regular Expressions (BRE) – Revisited

Three more additional types of expressions are:

The repeated patterns - &

The interval regular expression (IRE) – { }

The tagged regular expression (TRE) – ( )

The repeated patterns - &

To make the entire source pattern appear at the destination also

sed ‘s/director/executive director/’ emp.lst

sed ‘s/director/executive &/’ emp.lst

sed ‘/director/s//executive &/’ emp.lst

Replaces director with executive director where & is a repeated pattern

Coastal Institute of Technology and Management

Page 40: Record UnixIT

40

The interval RE - { }

sed and grep uses IRE that uses an integer to specify the number of characters preceding a pattern. The IRE uses an escaped pair of curly braces and takes three forms:

ch\{m\} – the ch can occur m times

ch\{m,n\} – ch can occur between m and n times

ch\{m,\} – ch can occur at least m times

The value of m and n can't exceed 255. Let teledir.txt maintains landline and mobile phone numbers. To select only mobile numbers, use IRE to indicate that a numerical can occur 10 times.

grep ‘[0-9]\{10\}’ teledir.txt

Line length between 101 and 150

grep ‘^.\{101,150\}$’ foo

Line length at least 101

sed –n ‘/.{101,\}/p’ foo

The Tagged Regular Expression (TRE)

You have to identify the segments of a line that you wish to extract and enclose each segment with a matched pair of escaped parenthesis. If we need to extract a number, \([0-9]*\). If we need to extract non alphabetic characters,

\([^a-zA-Z]*\)

Every grouped pattern automatically acquires the numeric label n, where n signifies the nth group from the left.

sed ‘s/ \ (a-z]*\) *\ ([a-z]*\) / \2, \1/’ teledir.txt

To get surname first followed by a , and then the name and rest of the line. sed does not use compulsorily a / to delimit patterns for substitution. We can use only any character provided it doesn’t occur in the entire command line. Choosing a different delimiter has allowed us to get away without escaping the / which actually occurs in the pattern.

Coastal Institute of Technology and Management

Page 41: Record UnixIT

41

Basic File Attributes:

The UNIX file system allows the user to access other files not belonging to them and without infringing on security. A file has a number of attributes (properties) that are stored in the inode. In this chapter, we discuss,

• ls –l to display file attributes (properties)• Listing of a specific directory• Ownership and group ownership• Different file permissions

Listing File Attributes

ls command is used to obtain a list of all filenames in the current directory. The output in UNIX lingo is often referred to as the listing. Sometimes we combine this option with other options for displaying other attributes, or ordering the list in a different sequence. ls look up the file’s inode to fetch its attributes. It lists seven attributes of all files in the current directory and they are:

• File type and Permissions• Links• Ownership• Group ownership• File size• Last Modification date and time• File name•The file type and its permissions are associated with each file. Links indicate the number of

file names maintained by the system. This does not mean that there are so many copies of the file. File is created by the owner. Every user is attached to a group owner. File size in bytes is displayed. Last modification time is the next field. If you change only the permissions or ownership of the file, the modification time remains unchanged. In the last field, it displays the file name.

For example,

$ ls –l

total 72

-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01

-rw-r--r-- 1 kumar metal 4174 may 10 15:01 chap02

-rw-rw-rw- 1 kumar metal 84 feb 12 12:30 dept.lst

-rw-r--r-- 1 kumar metal 9156 mar 12 1999 genie.sh

drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir

drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs

Coastal Institute of Technology and Management

Page 42: Record UnixIT

42

Listing Directory Attributes

ls -d will not list all subdirectories in the current directory

For example,

ls –ld helpdir progs

drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir

drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs

Directories are easily identified in the listing by the first character of the first column, which here shows a d. The significance of the attributes of a directory differs a good deal from an ordinary file. To see the attributes of a directory rather than the files contained in it, use ls –ld with the directory name. Note that simply using ls –d will not list all subdirectories in the current directory. Strange though it may seem, ls has no option to list only directories.

File Ownership

When you create a file, you become its owner. Every owner is attached to a group owner. Several users may belong to a single group, but the privileges of the group are set by the owner of the file and not by the group members. When the system administrator creates a user account, he has to assign these parameters to the user:

The user-id (UID) – both its name and numeric representation

The group-id (GID) – both its name and numeric representation

File Permissions

UNIX follows a three-tiered file protection system that determines a file’s access rights. It is displayed in the following format:

Filetype owner (rwx) groupowner (rwx) others (rwx)

For Example:

-rwxr-xr-- 1 kumar metal 20500 may 10 19:21 chap02

r w x r - x r - -

owner/user group owner others

The first group has all three permissions. The file is readable, writable and executable by the owner of the file. The second group has a hyphen in the middle slot, which indicates the absence of write permission by the group owner of the file. The third group has the write and execute bits absent. This set of permissions is applicable to others.

You can set different permissions for the three categories of users – owner, group and others. It’s important that you understand them because a little learning here can be a dangerous thing. Faulty file permission is a sure recipe for disaster

Coastal Institute of Technology and Management

Page 43: Record UnixIT

43

Changing File Permissions

A file or a directory is created with a default set of permissions, which can be determined by umask. Let us assume that the file permission for the created file is -rw-r--r--. Using chmod command, we can change the file permissions and allow the owner to execute his file. The command can be used in two ways:

In a relative manner by specifying the changes to the current permissions

In an absolute manner by specifying the final permissions

Relative Permissions

chmod only changes the permissions specified in the command line and leaves the other permissions unchanged. Its syntax is:

chmod category operation permission filename(s)

chmod takes an expression as its argument which contains:

user category (user, group, others)

operation to be performed (assign or remove a permission)

type of permission (read, write, execute)

Category operation permission

u - user + assign r - read

g - group - remove w - write

o - others = absolute x - execute

a - all (ugo)

Let us discuss some examples:

Initially,

-rw-r--r-- 1 kumar metal 1906 sep 23:38 xstart

chmod u+x xstart

-rwxr--r-- 1 kumar metal 1906 sep 23:38 xstart

The command assigns (+) execute (x) permission to the user (u), other permissions remain unchanged.

chmod ugo+x xstart or

chmod a+x xstart or

chmod +x xstart

Coastal Institute of Technology and Management

Page 44: Record UnixIT

44

-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart

chmod accepts multiple file names in command line

chmod u+x note note1 note3

Let initially,

-rwxr-xr-x 1 kumar metal 1906 sep 23:38 xstart

chmod go-r xstart

Then, it becomes

-rwx--x--x 1 kumar metal 1906 sep 23:38 xstart

Absolute Permissions

Here, we need not to know the current file permissions. We can set all nine permissions explicitly. A string of three octal digits is used as an expression. The permission can be represented by one octal digit for each category. For each category, we add octal digits. If we represent the permissions of each category by one octal digit, this is how the permission can be represented:

Read permission – 4 (octal 100) Write permission – 2 (octal 010) Execute permission – 1 (octal 001)

Octal Permissions Significance

0 - - - no permissions

1 - - x execute only

2 - w - write only

3 - w x write and execute

4 r - - read only

5 r - x read and execute

6 r w - read and write

7 r w x read, write and execute

We have three categories and three permissions for each category, so three octal digits can describe a file’s permissions completely. The most significant digit represents user and the least one represents others. chmod can use this three-digit string as the expression.

Coastal Institute of Technology and Management

Page 45: Record UnixIT

45

Using relative permission, we have,

chmod a+rw xstart

Using absolute permission, we have,

chmod 666 xstart

chmod 644 xstart

chmod 761 xstart

will assign all permissions to the owner, read and write permissions for the group and only execute permission to the others.

777 signify all permissions for all categories, but still we can prevent a file from being deleted. 000 signifies absence of all permissions for all categories, but still we can delete a file. It is the directory permissions that determine whether a file can be deleted or not. Only owner can change the file permissions. User can not change other user’s file’s permissions. But the system administrator can do anything.

The Security Implications

Let the default permission for the file xstart is

-rw-r--r--

chmod u-rw, go-r xstart or

chmod 000 xstart

----------

This is simply useless but still the user can delete this file

On the other hand,

chmod a+rwx xstart

chmod 777 xstart

-rwxrwxrwx

The UNIX system by default, never allows this situation as you can never have a secure system. Hence, directory permissions also play a very vital role here

We can use chmod Recursively.

chmod -R a+x shell_scripts

This makes all the files and subdirectories found in the shell_scripts directory, executable by all users. When you know the shell meta characters well, you will appreciate that the * doesn’t match filenames beginning with a dot. The dot is generally a safer but note that both commands change the permissions of directories also.

Coastal Institute of Technology and Management

Page 46: Record UnixIT

46

Directory Permissions

It is possible that a file cannot be accessed even though it has read permission, and can be removed even when it is write protected. The default permissions of a directory are,

rwxr-xr-x (755)

A directory must never be writable by group and others

Example:

mkdir c_progs

ls –ld c_progs

drwxr-xr-x 2 kumar metal 512 may 9 09:57 c_progs

If a directory has write permission for group and others also, be assured that every user can remove every file in the directory. As a rule, you must not make directories universally writable unless you have definite reasons to do so.

Changing File Ownership

Usually, on BSD and AT&T systems, there are two commands meant to change the ownership of a file or directory. Let kumar be the owner and metal be the group owner. If sharma copies a file of kumar, then sharma will become its owner and he can manipulate the attributes

chown changing file owner and chgrp changing group owner

On BSD, only system administrator can use chown

On other systems, only the owner can change both

chown

Changing ownership requires superuser permission, so use su command

ls -l note

-rwxr----x 1 kumar metal 347 may 10 20:30 note

chown sharma note; ls -l note

-rwxr----x 1 sharma metal 347 may 10 20:30 note

Once ownership of the file has been given away to sharma, the user file permissions that previously applied to Kumar now apply to sharma. Thus, Kumar can no longer edit note since there is no write privilege for group and others. He can not get back the ownership either. But he can copy the file to his own directory, in which case he becomes the owner of the copy.

Coastal Institute of Technology and Management

Page 47: Record UnixIT

47

SOLUTIONS FOR PROGRAMS:

WEEK 1

SESSION 1:

A) Aim : Log into the systemWhen we return on the system one screen will appear. In this we have to type 192.168.1.61 then we enter into editor. It asks our details such as

Login : citm

password:

Then we get log into the commands.

B) Aim : Use vi editor to create a file called myfile.txt which contains some text.To create a file in vi editor we must follow the syntax given below

Syntax:-vi file name

Here we have to open a file named as my file text when we open the file by using the above syntax one window will be opened in that we type text as our wish.

Example: vi myfile.text.

C) Aim : Correct typing errors during creation.

In creating a file through vi editor an error an error will occur we

modify the file by opening the file again. An error will occur when

we don’t give space between filename and command name

Example: vi530

Other type of error is when any wrong typing in file.

D) Aim: Save the File.

To save the file created in vi editor we press esc:WQ1.It means

that saves the file and Quits editing mode .then we come out from

the vi editor.

E) Aim : Logout the system.

Coastal Institute of Technology and Management

Page 48: Record UnixIT

48

In our current directory press exit to log out from the commands .In desktop turn of f computer option will displayed Ok that option and then ok shutdown option then windows will shutdown and we log out from the system.

SESSION 2:

A) Aim: Log into the system

When we turn on the system one screen will appear. In this we have to type 192.168.1.61 then we enter into editor. It asks

Login : citm

password:

Then we log into the commands.

B) Aim: Open the file created in session -1

In the above session we create a file in vi editor To open the

file created in Session 1 we have to type as follows

Syntax: vi filename

It displays the file as follows

C) Aim: Add Some text:

To add some text to the file which is already created first we have to open that file then add text.

vi filename. Text

D) Aim: Change some text

To change the some text in myfile.text move the cursor where we want to change the text After that replace the text under cursor with other text first open the file as follows.

vi myfile.text

E) Aim: Delete some text :

To delete text in my file text we first move the cursor to end of that line and then press delete then the line is erased to do this first we open the file as

vi myfile.text

F) Aim: Save the changes:

To save the changes made in file myfile.text we press

Coastal Institute of Technology and Management

Page 49: Record UnixIT

49

esc:WQ

It means that saves the file and quits editing mode then we log out from the vi Mode.

G) Aim: Logout of the System:

In our current directory press exit to logout from the commands in desktop turn off computer option will appear ok that option and then ok shutdown option then windows will shutdown we logout from the system.

WEEK 2

A) Aim : Log into the systemWhen we turn on the system one screen will appear in this we have to type 192.168.1.61 then we log into the commends it asks

Login : citm530

password:

then we log into the commands.

B) Aim : Use the cat command to create a file containing the following data .Call it mytable use

Coastal Institute of Technology and Management

Page 50: Record UnixIT

50

tabs to separate the fields.

1425 Ravi 15.65

4320 Ramu 26.27

6830 Sita 36.15

1450 Raju 21.86

Cat command is used to create the files Here file name is mytable

Example: cat>mytable

Type the file as given above

$ cat >mytable

1425 Ravi 15.65

4320 Ramu 26.27

6830 Sita 36.15

1450 Raju 21.86

To save the file press Ctrl + D

C) Aim: Use the Cat command to display the file,mytable.

To display the text in my table we use the syntax as follows

Syntax: cat mytable

It display the file as follows

$ cat mytable

1425 Ravi 15.65

4320 Ramu 26.27

6830 Sita 36.15

1450 Raju 21.86

D) Aim: Use the vi command to correct any errors in the file ,mytable

By using vi editor we have to correct errors occurred in creating file .

Open the file in vi editor as

Vi mytable

Coastal Institute of Technology and Management

Page 51: Record UnixIT

51

Use vi command to correct errors

E) Aim: Use the sort command to sort the file mytable according to the first field. Call the

sorted my table (same name)

short command is used to print the contents of the file in alphabetical order

syntax: sort filename

example: sort mytable.

$ sort -k 1 mytable > sortfile;cp sortfile mytable

cp: overwrite `mytable'? Y

$ cat mytable

1425 Ravi 15.65

1450 Raju 21.86

4320 Ramu 26.27

6830 Sita 36.15

F) Aim: print the file mytable

To print the file mytable we use cat command as follows

Syntax: cat filename

Example: cat myfile

$ lp mytable

1425 Ravi 15.65

1450 Raju 21.86

4320 Ramu 26.27

6830 Sita 36.15

G) Aim: use the cut and paste commands to swap fields 2 and 3 of mytable.Call it my table(same name)

By using cut command we cut fields as well as characters from the file cut command cuts mentioned characters and it is stored in another file as follows

cut –c characters my table >my

Coastal Institute of Technology and Management

Page 52: Record UnixIT

52

the fields are removed by using the syntax as follows the out put is stored in table

cut –f fields mytable >table

example: cut –f 1,3 mytable>my

It means it cuts 1,3 fields the middle part is stored in my file

Cut –c 5,9 mytable>table

It means it cuts the characters from 5 to 9 the remaining 1,3 fields are stored in table .To paste these two files we use paste command

Syntax: paste file1,file2

$ cat mytable

1425 Ravi 15.65

4320 Ramu 26.27

6830 Sita 36.15

1450 Raju 21.86

$ cut -f 1 mytable >field1;cut -f 2 mytable >field2;cut -f 3 mytable>field3

$ paste field1 field3 field2 > mytable

$ cat mytable

1425 15.65 Ravi

4320 26.27 Ramu

6830 36.15 Sita

1450 21.86 Raju

H) Aim:Print the new file,mytable

The file swapped this file can be displayed as follows

$ lp mytable

1425 15.65 Ravi

4320 26.27 Ramu

6830 36.15 Sita

1450 21.86 Raju

Coastal Institute of Technology and Management

Page 53: Record UnixIT

53

I) Aim: logout of the system.

In our current directory type exit to log out from the commands in desktop turnoff computer option will appear ok that option and then ok shutdown option then windows will shutdown we logout from the system.

Logout

[ctrl-d] or

Exit

WEEK 3

1. A) Aim: login to the system

When we turn on the system one screen will appear in this we have to type 192.168.1.61 then we enter into one window it asks

Login : citm

password:

Then we login to the commands

B) Aim: use the appropriate command to determine your login shell

If we want to known in which shell you login shell the syntax is as follows

Syntax: $ echo $SHELL

$ echo $SHELL

/bin/bash

Unix contains a system variable shell that identifiers the path to your login shell

Aim: use the /etc/passwd file to verify the result of step b.

By using cat command we can print who login in to the system

$ cd /

$ ls

Coastal Institute of Technology and Management

Page 54: Record UnixIT

54

bin dev lib media net root srv usr

boot etc home .............. linux tmp

$ cd etc

$ ls

a2ps,a2ps.cfg, initlog.conf,......... , passwd, passwd-

................................

$ cat passwd

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

....................................................

...................................................

citm:x:501:501:Citmrushi:/home/citm:/bin/bash

D) Aim: use the who command and redirect the result to a file called myfile1.Use the more command to see the contents of myfile1.

When we redirect the standard output the command output is copy to a file rather than displayed on the monitor the redirection operator for output is >

Command >file name

Who>myfile1

The result of who command is stored in myfile1

By using more command we print the myfile1 contents as follows

More myfile1

$ who >myfile1

$ more myfile1

citm tty7 2009-08-23 09:08 (:0)

citm pts/1 2009-08-23 09:09 (:0.0)

.......... ....... .......................................

.......... ....... .......................................

Coastal Institute of Technology and Management

Page 55: Record UnixIT

55

E) Aim: Use the date and who commands in sequence (in one line) such that the output of date will display on the screen and the output of who will be redirected to a file called myfile2. use the more command to check the contents of myfile2.

In sequence command sequence of commands can be entered on oneline

$ date;who > myfile2

Sat Aug 23 09:38:05 IST 2009

$ more myfile2

citm tty7 2009-08-23 09:08 (:0)

citm pts/1 2009-08-23 09:09 (:0.0)

......... . ....... .......................................

2. A) Aim: Write a sed command that deletes the first character

in each line in a file.

#Delete the first character in each line in a file.

$ cat mytable

1425 Ravi 15.65

4320 Ramu 26.27

6830 Sita 36.15

1450 Raju 21.86

7820 Anil 23.34

9000 Citm 35.56

$ sed 's/^./ / ' mytable

425 Ravi 15.65

320 Ramu 26.27

830 Sita 36.15

450 Raju 21.86

820 Anil 23.34

000 Citm 35.56

B) Aim: Write a sed command that deletes the character before the

last character in each line in a file.

Coastal Institute of Technology and Management

Page 56: Record UnixIT

56

# Delete the last character in each line in a file.

$ sed 's/.$/ /' mytable

1425 Ravi 15.6

4320 Ramu 26.2

6830 Sita 36.1

1450 Raju 21.8

7820 Anil 23.3

9000 Citm 35.5

C) Aim: Write a sed command that swaps the first and second words in a file.

# Swaps the first and second words in each line in a file.

$ sed ‘s/ \([^ ]*\) *\([^ ]*\)/ \2 \1 /g’ mytable

Ravi 1425 15.65

Ramu 4320 26.27

Sita 6830 36.15

Raju 1450 21.86

Anil 7820 23.34

Citm 9000 35.56

WEEK 4

Coastal Institute of Technology and Management

Page 57: Record UnixIT

57

A) Aim : pipe your /etc/passwd file to awk , and print out the home directory of each user.First we go to vi editor by using

$ vi home.awk

{

if(match ($0, /^.*home/) > 0)

{

split( $0, user)

split(user[1],homedir, ":")

print homedir[1]

}

}

To compile the program use

Sh filename.sh

To return the program

awk command :

$ cat /etc/passwd | awk -f home.awk

Administrator

Guest

sys1

IT

IT123

it

IT501

IT502

B) Aim: Develop an interactive grep script that asks for a word and a

file name and then tells how many lines contain that word.

First we create a file with filename grep.sh

$ vi grep.sh

Coastal Institute of Technology and Management

Page 58: Record UnixIT

58

echo "Enter the pattern to be searched: "

read pattern

echo "Enter the file to be used: "

read filename

echo "Searching for $pattern from file $filename"

echo "The selected records are: "

grep "$pattern" $filename

echo "The no.of lines contains the word( $pattern ) :"

grep -c "$pattern" $filename

Output :

$ sh grep.sh

Enter the pattern to be searched:

computer

Enter the file to be used:

sales.dat

Searching for computer from file sales.dat

The selected records are:

10 computer 2345

10 computer 7685

The no.of lines contains the words ( computer ) :

WEEK 5

A) Aim : write a shell script that takes a command –line argument and reports on whether it is

directory, a file, or something else.

$ vi filetype.sh

echo "Enter the file name: "

Coastal Institute of Technology and Management

Page 59: Record UnixIT

59

read file

if [ -f $file ]

then

echo $file "---> It is a ORDINARY FILE."

elif [ -d $file ]

then

echo $file "---> It is a DIRCTORY."

else

echo $file "---> It is something else."

fi

outputs:

$ sh filetype.sh

Enter the file name:

sales.dat

sales.dat ---> It is a ORDINARY FILE.

$ sh filetype.sh

Enter the file name:

IT

IT---> It is a DIRCTORY.

B) Aim : Write a shell script that accepts one or more file name as arguments and converts all of them to uppercase, provided they exist in

the current directory.

$vi upper.sh

for file in *

do

if [ -f $file ]

then

echo $file | tr '[a-z]' '[A-Z]'

fi

Coastal Institute of Technology and Management

Page 60: Record UnixIT

60

done

Reading input :

$ ls

afile

afile1.tar

afile.tar

aped.sed

errfile

exch.dat

exsed.sed

f1

for.sh

grep.sh

Output:

$ sh upper.sh

AFILE

AFILE.TAR

APED.SED

ERRFILE

EXCH.DAT

EXSED.SED

F1

FOR.SH

GREP.SH

C) Aim : Write a shell script that determines the period for which a specified user is working On the system.

$vi logtime.sh

echo "Enter the USER NAME : "

Coastal Institute of Technology and Management

Page 61: Record UnixIT

61

read user

last $user

Output :

$ sh logtime.sh

Enter the USER NAME :

IT123

IT123 tty7 :0 Fri Sep 26 13:27 still logged in

IT123 pts/1 :0.0 Thu Sep 25 15:08 - 15:45 (00:37)

IT123 tty7 :0 Thu Sep 25 14:53 - 16:32 (01:39)

IT123 tty7 :0 Thu Sep 25 14:13 - 14:25 (00:11)

IT123 tty7 :0 Tue Sep 23 13:54 - 15:30 (01:36)

IT123 pts/2 :20.0 Mon Sep 22 17:02 - 17:23 (00:21)

WEEK 6

A) Aim : write a shell script that accepts a file name starting and ending line numbers as arguments and displays all the lines between the given line numbers.$ vi range.sh

echo " Enter the file name :"

read file

if [ -f $file ]

then

echo "Enter the Starting line number:"

read snum

echo "Enter the Ending line number:"

read enum

if [ $snum -lt $enum ]

then

echo "The selected lines from $snum line to $enum line in $file :"

Coastal Institute of Technology and Management

Page 62: Record UnixIT

62

sed -n ' ' $snum','$enum' 'p' ' $file

else

echo "Enter proper starting & ending line numbers."

fi

else

echo "The file ' $file ' doesn't exists. "

fi

Output:

$sh range.sh

Enter the file name :

sales.dat

Enter the Starting line number:

2

Enter the Ending line number:

4

The selected lines from 2 line to 4 line in sales.dat :

11 tvsets 8765

10 computer 7685

12 mouse 6785

B) Aim : write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. $ vi detline.sh

echo "Enter the word to search for all lines :"

read word

echo "the file name are $* ."

for i in $*

do

Coastal Institute of Technology and Management

Page 63: Record UnixIT

63

echo "The name of the file :" $i

grep -v $word $i

done

Output :

$ sh detline.sh sales.dat sales1.dat sales2.dat

Enter the word to search for all lines :

computer

the file name are sales.dat sales1.dat sales2.dat

The name of the file : sales.dat

11 tvsets 8765

12 mouse 6785

13 keyboard 2341

The name of the file : sales1.dat

11 tvsets 8765

12 mouse 6785

13 keyboard 2341

The name of the file : sales2.dat

11 tvsets 8765

12 mouse 6785

13 keyboard 2341

Coastal Institute of Technology and Management

Page 64: Record UnixIT

64

WEEK 7

A) Aim : write a shell script that computes the gross salary of a employee according to the following rules:i ) If basic salary is <1500 then HRA=10% of the basic and DA=90% of the basic

ii) If the basic salary is>=1500 then HRA=500/- and DA=98% of the basic

The basic salary is entered interactively through the key board.

$ vi gsalary.sh

echo "enter the basic salary:"

read bsal

if [ $bsal -lt 1500 ]

then

gsal=$((bsal+((bsal/100)*10)+(bsal/100)*90))

echo "The gross salary : $gsal"

fi

if [ $bsal -ge 1500 ]

then

gsal=$(((bsal+500)+(bsal/100)*98))

echo "the gross salary : $gsal"

fi

Output :

$ sh gsalary.sh

enter the basic salary:

1200

The gross salary : 2400

Coastal Institute of Technology and Management

Page 65: Record UnixIT

65

$ sh gsalary.sh

enter the basic salary:

2400

the gross salary : 5252

B) Aim : Write a shell script that accepts two integers as its arguments and computers the value of first number raised to the power of the second number.

$ vi pow.sh

echo "Enter the integer value :"

read int1

echo "Enter the power of that integer:"

read int2

pv=$int1

i=1

while [ $i -lt $int2 ]

do

pv=`expr $pv \* $int1`

i=`expr $i + 1 `

done

echo "The value of first number to the power of the second number :"

echo "$pv"

output:

$ sh pow.sh

Enter the integer value :

2

Enter the power of that integer:

5

The value of first number to the power of the second number : 32

WEEK 8

Coastal Institute of Technology and Management

Page 66: Record UnixIT

66

A) Aim : Write an interactive file –handling shell program. Let it offer the user the choice of copying removing, renaming, or linking files. Once the user has made a choice, have the same program ask the user for the necessary information, such as the file name ,new name and so on.

$ cat 8a.sh

echo "*******MENU*********"

echo "

1. List of files.

2. Copying files.

3. Removing files.

4. Renaming files.

5. Linking files."

Echo "enter your choice "

read ch

case "$ch" in

1 ) echo "The list of file names."

ls –l

2 ) echo "Enter the old filename."

read ofile

echo "Enter the new file name."

read nfile

cp $ofile $nfile && echo "Copied sucessfully." || echo

"Copied is not possible." ;;

3 ) echo "Enter the file name to remove."

read rfile

rm -f $rfile && echo "Successfully removed." ;;

4 ) echo "Enter the old file name."

read ofile

Coastal Institute of Technology and Management

Page 67: Record UnixIT

67

echo "Enter the new file name."

read nfile

mv $ofile $nfile && echo "The file $ofile name renamed

to $nfile." || echo "You cann't Rename the file. “;;

5 ) echo "Enter the original filename."

read ofile

echo "Enter the new filename to link a file."

read lfile

ln $ofile $lfile && echo "Creat the linking file

Sccessfully." || echo "You cann't Linking the file.";; * )

echo "Invalid option."

Echo " Enter correct choice."

esac

Output :

$ sh 8a.sh

*******MENU*********

1. List of files.

2. Copying files.

3. Removing files.

4. Renaming files.

5. Linking files.

enter your choice

2

Enter the old filename.

f1

Enter the new file name.

f0

Coastal Institute of Technology and Management

Page 68: Record UnixIT

68

Copied sucessfully.

B) Aim: Write shell script that takes a login name as command-line argument and reports when that person logs in.

$vi login.sh

echo "Enter the USER NAME : "

read user

last $user

Output :

$ sh logtime.sh

Enter the USER NAME :

IT123

IT123 tty7 :0 Fri Sep 26 13:27 still logged in

IT123 pts/1 :0.0 Thu Sep 25 15:08 - 15:45 (00:37)

IT123 tty7 :0 Thu Sep 25 14:53 - 16:32 (01:39)

IT123 tty7 :0 Tue Sep 23 13:54 - 15:30 (01:36)

IT123 pts/2 :20.0 Mon Sep 22 17:02 - 17:23 (00:21)

(or)

echo “ The Login repots of the user : $* .”

last $*

output :

$sh login.sh IT123

IT123 tty7 :0 Fri Sep 26 13:27 still logged in

IT123 pts/1 :0.0 Thu Sep 25 15:08 - 15:45 (00:37)

IT123 tty7 :0 Thu Sep 25 14:53 - 16:32 (01:39)

IT123 tty7 :0 Thu Sep 25 14:13 - 14:25 (00:11)

C) Aim: Write a shell script which receives two file names as arguments. It should check whether the two file contents are same or not. If they are same then second file should be deleted.

$vi cheek.sh

Coastal Institute of Technology and Management

Page 69: Record UnixIT

69

echo "enter the first file name"

read file1

echo "enter the second file name"

read file2

cmp $file1 $file2 && rm $file2

if [ -e $file1 ]

then

if [ ! –e $file2 ]

then

echo "The two files contents are same."

echo "The second file is deleted successfully."

else

echo "The two files contents are not same."

echo "You cann't remove the file '$file2' ."

fi

else

echo "You should enter the existing file names."

fi

Output:

$ sh cheek.sh

enter the first file name

file1.dat

enter the second file name

file3.dat

The two files contents are same.

The second file is deleted successfully.

$ sh 8c.sh

enter the first file name

Coastal Institute of Technology and Management

Page 70: Record UnixIT

70

file1.dat

enter the second file name

file2.dat

file1.dat file2.dat differ: byte 1, line 1

The two files contents are not same.

You cann't remove the file 'file2.dat' .

$ sh 8c.sh

enter the first file name

file5.dat

enter the second file name

file3.dat

cmp: file3.dat: No such file or directory

You should enter the existing file names.

WEEK 9

A) Aim : write a shell script that displays a list of all the files in the current directory to which the use has read ,write and execute permissions.$vi perm.sh

echo "The list of File Names in the curent directory."

echo "Which have Read,Write and Execute permisions. "

for file in *

do

if [ -f $file ]

then

if [ -r $file -a -w $file -a -x $file ]

then

ls -l $file

fi

fi

done

Coastal Institute of Technology and Management

Page 71: Record UnixIT

71

Output :

$chmod 777 file1

$chmod 777 file2

$chmod 777 file3

$chmod 777 file4

$ sh perm.sh

The list of File Names in the curent directory.

Which have Read,Write and Execute permisions.

-rwxrwxr-x 1 citm citm 6722 2009-08-21 10:00 a.out

-rwxrwxrwx 1 citm citm 4 2009-08-18 16:48 file1

-rwxrwxrwx 1 citm citm 9 2009-08-18 16:48 file2

-rwxrwxr-x 1 citm citm 4 2009-08-19 14:33 file3

-rwxrwxrwx 1 citm citm 14 2009-08-18 16:48 file4

B) Aim : Develop an interactive script that ask for a word and a file name and then tells how many times that word occurred in the file.$ vi wcount.sh

echo " Enter the word to be searched"

read word

echo "Enter the filename to be used"

read flname

echo "the no. of times the word occured in the file."

grep -c $word $flname

Output:

$ sh wcount.sh

Enter the word to be searched

computers

Enter the filename to be used

sales.dat

Coastal Institute of Technology and Management

Page 72: Record UnixIT

72

the no. of times the word occured in the file.

2

C) Aim: Write a shell script to perform the following string operations:

I) To extract a sub-string from a given string.II) To find the length of a given string.

$ vi strlen.sh

echo "To find the length of the given string."

echo "Enter the string."

read string

strlen=${#string}

echo "The string length is : $strlen"

Output :

$ sh strlen.sh

To find the length of the given string.

Enter the string.

computer science and engineering.

The string length is : 33

Coastal Institute of Technology and Management

Page 73: Record UnixIT

73

WEEK 10

A) Aim: Write a C program that takes one or more file or directory names

as command line input and reports the following information on the file:

I)file type

#include<stdio.h>

#include<unistd.h>

#include<sys/stat.h>

#include<sys/types.h>

int main(int argc,char *argv[])

{

struct stat b;

int i;

for(i=1;i<argc;i++)

{

if(lstat(argv[i],&b)==-1)

{

printf("%s",argv[i]);

fflush(stdout);

perror("lstat error");

continue;

}

else if(S_ISREG(b.st_mode))

printf("regular file\n");

Coastal Institute of Technology and Management

Page 74: Record UnixIT

74

else if(S_ISDIR(b.st_mode))

printf("directory file \n");

else if(S_ISCHR(b.st_mode))

printf("character special file\n");

else if(S_ISBLK(b.st_mode))

printf("block special file \n");

else if(S_ISFIFO(b.st_mode))

printf("pipefile \n");

else if(S_ISLNK(b.st_mode))

printf("symbloic link file");

else if(S_ISSOCK(b.st_mode))

printf("socket file \n");

else

printf("unknown file");

}

}

OUTPUT :

$./a.out lab1.sh

regular file

B) Aim: Write a C program that takes one or more file or directory names as

command line input and reports the following information on the file:

Coastal Institute of Technology and Management

Page 75: Record UnixIT

75

(i) file type

(ii) number of links

(ii) read, write and execute permission

(iv) time of last access

#include<sys/stat.h>

#include<stdio.h>

#include<unistd.h>

#include<stdlib.h>

int main(int argc,char *argv[])

{

struct stat statbuf;

int i;

if(argc<2)

{

printf("usage:./a.out< filename(s)");

exit(1);

}

for(i=1;argc!=i;i++)

{

if(access(argv[i],F_OK)<0)

{

printf(" \n %s,File/dir not exists",argv[i]);

continue;

}

else

{

if(lstat(argv[i],&statbuf)<0)

{

Coastal Institute of Technology and Management

Page 76: Record UnixIT

76

printf("unable to read Status of file :%s",argv[i]);

continue;

}

printf("No of links :%d \t",statbuf.st_nlink);

}

}

return(0);

}

OUTPUT :

No of links :1

Last access time is 1207834720

Read permissions for the user

Write permissions for the user

Execute permissions for the user

WEEK 11

A) Aim: Write a C program that simulate the following UNIX commands:

a) mv

#include<unistd.h>

#include<stdio.h>

#include<stdlib.h>

int main(int argc,char *argv[])

Coastal Institute of Technology and Management

Page 77: Record UnixIT

77

{

if(argc!=3)

{

printf("usage:a.out <old name> <new name>");

exit(1);

}

if(access(argv[1],F_OK)<0)

{

if("File not found");

exit(2);

}

if(rename(argv[1],argv[2])<0)

{

printf("Rename Error");

exit(3);

}

printf("%s renamed as %s",argv[1],argv[2]);

return 0;

}

OUTPUT :

$./a.out lab8c.c lab8b.c

lab8c.c renamed as lab8b.c

B) Aim: Write a C program that simulate the following UNIX commands:

b) cp (use system calls)

#include<stdio.h>

Int main(int argc,char *argv[])

{

FILE *fp1,*fp2;

Coastal Institute of Technology and Management

Page 78: Record UnixIT

78

int ch;

fp1=fopen(argv[1],”r”);

fp2=fopen(argv[2],”r”);

while((ch=fgtc(fp1))!=-1)

fputc(ch,fp2);

}

OUT PUT:

Cc filename c

La out ab abc

This is CITM College.

WEEK 12

A) Aim: Write a C program that simulates ls command (use system calls/directory API)

#include<stdio.h>

#include<conio.h>

#include<unistd.h>

#include<derent.h>

Int main()

{

DIR *dirp;

Struct dirent *dp;

Dirp=opendir(“”);

If(dirp==NULL)

Coastal Institute of Technology and Management

Page 79: Record UnixIT

79

Printf(“error”);

else

for(dp=readdir(dirp);dp!=NULL;dp=readdir(dirp))

printf(“%s\n”,dp->d=name);

}

Output:

cc filename c

la.output

a.out

ramesh

file1

file2

Coastal Institute of Technology and Management