Unix Lab

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

UNIX MANUAL

P.N.V.SUNIL KUMAR

INDEX S.No
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Lab Objective Guidelines to Students Some Common Commands Operations Unique to Directories Operations Unique to Regular Files Operation on both Directories and Files Filter Commands Remote Access Job Control and Aliases Changing Permissions VI Editor Introduction to Shell Lab Programs Viva Questions & Answers References

Contents

Page No.
3 4 6 10 11 12 15 21 22 24 25 26 27 51 61

P.N.V.SUNIL KUMAR

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. Use the following Bourne Shell constructs: test, if then, if then else, if then elif, for, while, until, and case. 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.
Copy, move, and delete files and directories

2. 3.

4.

5. 6. 7. 8. 9. 10.

Write moderately complex Shell scripts. Make a Shell script executable. Create a ".profile" script to customize the user environment. Use advanced features of File Transfer Protocol (FTP) Compile source code into object and executable modules. Execute programs written in c under UNIX environment

P.N.V.SUNIL KUMAR

Guidelines to Students
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 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

P.N.V.SUNIL KUMAR

How to run C programs Method 1: 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 show.c contains the following lines : main() { printf( welcome to UNIX Lab ); } Step 2 : Submit the file to CC ( the C Compiler ) $ cc show.c If the program is okay, the compiled version is placed in a file called a.out Step 3 : To run the program, type a.out $ a.out welcome to UNIX Lab Method 2: Syntax gcc -o output-file program.c Step 1: Compile program To compile type the command: $ gcc test.c Step 2: Execute program to see output Above command will create a file called a.out. To see output of test.c program type: $ ./a.out Step 1: Compile to specific executable file You can specify an execuable file name while compiling program itself: $ gcc -o test test.c Now execute test (see output of test.c) $ ./test

P.N.V.SUNIL KUMAR

COMMAND NAME

DESCRIPTION ,OPTIONS AND EXAMPLES COMMON COMMANDS Description: It displays the system date and time Syntax: date options arguments Options: -u universal Format Code : a abbreviated weekday, such as Mon A Full weekday name, such as Monday D Date in format mm/dd/yy p Display am or pm Example: [system43@localhost ~]$ date Sat Oct 31 14:10:08 IST 2009 [system43@localhost ~]$ date "+today's date is: %D.The Time is %T" today's date is: 10/31/09.The Time is 14:11:08 [system43@localhost ~]$ date -u Sat Oct 31 08:43:00 UTC 2009 Description: cal, It displays the calendar for a specified month or for a year. Syntax: cal options [[month]year] Options: -1 Display single month output (default) -3 Display prev/current/next month output. -s Display Sunday as the first day of the week. -m Display Monday as the first day of the week. -y Displays the calendar for the current year. Examples: [system43@localhost ~]$ cal -1 October 2009 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 [system43@localhost ~]$ cal -3 September 2009 October 2009 November 2009 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa [system43@localhost ~]$ cal -y Description : Displays all users currently logged in to the system. Syntax: who [OPTION]... [ FILE | ARG1 ARG2 ] Options : -u Idle time -H Header -l prints system login process Example: [system43@localhost ~]$ who system1 pts/1 2009-10-31 14:06 system43 pts/2 2009-10-31 14:10 (192.168.1.42) [system43@localhost ~]$ who -uH NAME LINE TIME IDLE PID COMMENT system43 pts/2 2009-10-31 14:10 . 3039 (192.168.1.42) [system43@localhost ~]$ who am i system43 pts/2 2009-10-31 14:10 (192.168.1.42) 6

Date (date)

Calendar (cal)

Who (who)

P.N.V.SUNIL KUMAR

Change password (passwd)

Description: It is used to change your password. Syntax : passwd options argument Example: [system43@localhost ~]$ passwd Changing password for user system43. Changing password for system43 (current) UNIX password: New UNIX password: Re-enter new password: Description: It copies its argument back to the terminal. Syntax: echo -options arguments Example: [system43@localhost ~]$ echo hello world hello world [system43@localhost ~]$ echo "hi how r u" hi how r u Description: It displays online documentation, it is one of the most imortant unix Command. Syntax: man -options keyword Options : -k search on keyword Example: [system43@localhost ~]$ man cal CAL(1) BSD General Commands Manual CAL(1) NAME cal - displays a calendar SYNOPSIS cal [-smjy13] [[month] year] DESCRIPTION Cal displays a simple calendar. If arguments are not specified, the current month is displayed. The options are as follows: -1 Display single month output. (This is the default.) -3 Display prev/current/next month output. Description: lpr submits files for printing. Files named on the command line are sent to the named printer. Syntax: lpr options file-list Options: -P printer Example: [system43@localhost ~]$ lpr -P file1 Description: It is used to show the name of the terminal you are using Syntax: tty options arguments Example: [system43@localhost ~]$ tty /dev/pts/2 Description: The clear command clears the screen and puts the cursor at the top Syntax: clear -options arguments Example: clear Description: It sets or unsets selected terminal input/output options Syntax: stty options arguments 7

Print message (echo)

Online document (man)

Print (lpr)

Terminal (tty)

Clear screen (clear)

Set terminal (stty) P.N.V.SUNIL KUMAR

Options: -a displays current settings (in human readable form) -g displays current settings (in argument format) ek argument sets erase and kill to their default sane sets all to general arguments Example: [system43@localhost ~]$ stty -a speed 9600 baud; rows 25; columns 80; line = 0; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0; [system43@localhost ~]$ stty erase ^e to use (ctrl+e) [system43@localhost ~]$ stty kill ^k to use (ctrl+k) Record session (script) Description: IT can be used to record an interactive session. IT makes type scripting of terminal session Default it takes script name as typescript Syntax: script options arguments Options: -a append Example : [system43@localhost ~]$ script file1 Script started, file is file1 [system43@localhost ~]$ date Sat Oct 31 15:12:42 IST 2009 [system43@localhost ~]$ cal October 2009 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 [system43@localhost ~]$ exit exit Script done, file is file1 [system43@localhost ~]$ cat file1 /* all the above i.e date and cal will be stored */ Description: For sending a group of files to someone either by FTP or email, it helps To combine them into a single file called an archive. The tar command is an archive Syntax: tar options fname.tar new-filename Options : -c creates an archive -x Extracts files from archive -t Displays files in archive -v verbose Examples: [system43@localhost ~]$ tar -cvf mm.tar ex1 // for directories ex1/ creating an archive. ex1/f4 ex1/ex2/ ex1/f2 ex1/f1 ex1/f3 [system43@localhost ~]$ ls -- 3a.sh 4a.sh echo ex1 f1 f2 f2.c f2.sh file1 mm.tar naveen [system43@localhost ~]$ rmdir ex1 8

Tap archive(tar)

P.N.V.SUNIL KUMAR

[system43@localhost ~]$ ls -- 3a.sh 4a.sh echo f1 f2 f2.c f2.sh file1 mm.tar naveen [system43@localhost ~]$ tar -xvf mm.tar // Extracting file ex1/ ex1/f4 ex1/ex2/ ex1/f2 ex1/f1 ex1/f3 [system43@localhost ~]$ ls -- 3a.sh 4a.sh echo ex1 f1 f2 f2.c f2.sh file1 mm.tar naveen [system43@localhost ~]$ tar -cvf m1.tar f1 f2 f1 f2 [system43@localhost ~]$ ls -- 3a.sh 4a.sh echo ex1 f1 f2 f2.c f2.sh ish m1.tar mm.tar [system43@localhost ~]$ tar -tvf m1.tar // To Display -rw-rw-r-- system43/system43 21 2009-11-26 14:05:47 f1 -rw-rw-r-- system43/system43 110 2009-12-10 10:40:22 f2 [system43@localhost ~]$ System name(uname) Description: Print system information Syntax: uname -option arguments Options: -a all -n name only -s operating system(prints kernel name) -r release Example: [system43@localhost ~]$ uname Linux [system43@localhost ~]$ uname -r 2.6.15-1.2054_FC5smp [system43@localhost ~]$ uname -a Linux localhost.localdomain 2.6.15-1.2054_FC5smp #1 SMP Tue Mar 14 16:05:46 ES2006 i686 i686 i386 GNU/Linux Description: bc is a language that supports arbitrary precision numbers with interactive execution of statements. It Turns UNIX in to calculator. IT supports +, - , *,/ Syntax: bc options arguments To terminate the be we use (ctrl+d) Examples: [system43@localhost ~]$ bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 2+5 7 34+5/5 35 (ctrl+d) [system43@localhost ~]$

Calculator (bc)

P.N.V.SUNIL KUMAR

Locate Directory(pwd)

OPERATIONS UNIQUE TO DIRECTORIES Description: It is used to determine the current directory it is print working directory Syntax: pwd options arguments Example : [system43@localhost ~]$ pwd /home/system43 Description: It lists the contents in a directory. Depending on the option used, it can List files, directories, or subdirectories. Syntax: ls options pathname Options : -l long list -r reverse order -d working directory -i print inode -t time sequence -a prints along with hidden files -x list entries by line instead of column -p Identify the directories Examples : [system43@localhost ~]$ ls 9a.sh b f1 kk saras week11a.c week4a.awk 9b.sh dd file1 kkk sarath week11b.c week4b.awk a.out dd.awk file3 mytable sunil week12.c [system43@localhost ~]$ ls -l total 88 -rw-rw-r-- 1 system43 system43 776 Oct 29 10:56 9a.sh -rw-rw-r-- 1 system43 system43 148 Oct 29 10:59 9b.sh -rwxrwxr-x 1 system43 system43 5431 Oct 29 12:56 a.out [system43@localhost ~]$ ls sunil a b [system43@localhost ~]$ ls ld // displays only the working directory drwx------ 5 system43 system43 4096 Oct 30 15:24 . Description: To create a new directory , we use mkdir command. Syntax: mkdir option dir-name Options: -m mode -p parents no error if existing, make parent directories as needed -v verbose print a message for each created directory -m set permission mode Examples: [system43@localhost ~]$ mkdir dir3 [system43@localhost ~]$ mkdir -p dir3/dir5 [system43@localhost ~]$ cd dir3 [system43@localhost dir3]$ ls dir5 [system43@localhost dir3]$ cd .. [system43@localhost ~]$ mkdir -v dir6 mkdir: created directory `dir6'

List Directory (ls)

Make directory(mkdir)

Change directory (cd)

Description: When we want to move from one directory to another directory i.e to Change the working directory we use the command cd. Syntax: cd options pathname Example: [system43@localhost ~]$ cd dir3 [system43@localhost dir3]$ cd .. // to come out from that directory use cd (space).. 10

P.N.V.SUNIL KUMAR

[system43@localhost ~]$ cd ~/dir3/dir5 // To move directly from home to dir5 [system43@localhost dir5]$ [system43@localhost dir5]$ cd // to move directly to the home directory use cd with Out any arguments [system43@localhost ~]$ Remove directory (rmir) Description: When a directory is not need it should be removed. The rmdir command Deletes directories. It cont delete a directory unless it is empty. Syntax: rmdir option dir-name Options: -p parents, Remove DIRECTORY and its ancestors -v verbose ,output a diagnostic for every directory processed Examples: [system43@localhost ~]$ rmdir -p dir3/dir5 [system43@localhost ~]$ rmdir -v dir6 rmdir: removing directory, dir6 [system43@localhost ~]$ rmdir sunil rmdir: sunil: Directory not empty [system43@localhost ~]$ OPERATIONS UNIQUE TO REGULAR FILES The most common tool to create a file is a text editor such as vi and cat , that are useful To create small files. UNIX provides several utilities to edit text files. The most common is a basic text Editor such as vi in addition to this we have sed Description: cat command it is used to create, display and appending of files Syntax: cat options inputfiles Options: -n number lines -t print tabs and form feeds -e print $ at end of each line -v print control characters Examples: [system43@localhost ~]$ cat > f1 // create a new file hello friends how r u wht r u doing come here its urgent [system43@localhost ~]$ cat > f2 when will u come be fast bye [system43@localhost ~]$ cat f1 f2 // to display multiple files at a time hello friends how r u wht r u doing come here its urgent when will u come be fast bye [system43@localhost ~]$ cat >> f1 // to append a data to the existing file where r u [system43@localhost ~]$ cat -nt f1 // To print line numbers and tab spaces in a file 1 hello friends how r 2 u wht r u doing 3 where r u 11

Create file (cat) Edit File Create or catenate (cat)

P.N.V.SUNIL KUMAR

4 come^Ihere^Iits^Iurgent // ^I indicates there is a tab space b/w the words Display file (more) Description: It allows us to set the output page size and pauses at the end of each Page to allow us to read the file. Syntax: more option inputfile Options: -c clear -lines lines per page -s Squeeze multiple blank lines into one. -u Suppress underlining. Examples: [system43@localhost ~]$ more -4 file2 // takes 4 lines per page of file file2 Script started on Sat 31 Oct 2009 03:12:39 PM IST [system43@localhost ~]$ date Sat Oct 31 15:12:42 IST 2009 [system43@localhost ~]$ cal --More--(36%) [system43@localhost ~]$ more file2 Script started on Sat 31 Oct 2009 03:12:39 PM IST [system43@localhost ~]$ date Sat Oct 31 15:12:42 IST 2009 [system43@localhost ~]$ cal October 2009 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 --More--(56%) Description: The line printer (lpr) prints the contents of the specified files to either the default printer or a specified printer. Multiple files can be printed with the same command. Syntax: lpr option file-list Options: -p printer Examples: [system43@localhost ~]$lpr file1 [system43@localhost ~]$lpr file1 file2 file3 OPERATIONS COMMON TO BOTH Description: It creates a duplicate of a file, a set of files or a directory. If the Destination file already exists; its contents are replaced by the source. Syntax: cp options source destination Options: -i interactive prompt -r recursive- copy sub directories -f force, if an existing destination file cannot be opened, remove it and try again -u update ,copy only when the SOURCE file is newer than the destination file or when the destination file is missing -v, verbose , explain what is being done Examples: [system43@localhost ~]$ cp f1 f2 [system43@localhost ~]$ cp -v f2 f3 // verbose 12

Print file (lpr)

Copy command (cp)

P.N.V.SUNIL KUMAR

`f2' -> `f3' [system43@localhost ~]$ ls dir1 d2 dir2 f1 f2 f3 [system43@localhost ~]$ ls dir2 dir1 f1 f3 file1 [system43@localhost ~]$ cp -r dir1/f2 dir2 // recursive [system43@localhost ~]$ ls dir2 dir1 f1 f2 f3 file1 [system43@localhost ~]$ cp -i f1 f2 // interactive cp: overwrite `f2'? y [system43@localhost ~]$cp dir1/f* dir2 // wildcard copies [system43@localhost ~]$ Move (or) rename command (mv) Description: It is used to move an individual file, a list of files, or a directory. After a move, the old file name is gone and a new file name is found at the destination. Syntax: mv option source destination Options: -i interactive prompt -f force, if an existing destination file cannot be opened, remove it and try again -u update ,copy only when the SOURCE file is newer than the destination file or when the destination file is missing -v, verbose , explain what is being done Examples: [system43@localhost ~]$ mv f2 f3 [system43@localhost ~]$ cat f2 cat: f2: No such file or directory [system43@localhost ~]$ cat f3 hello friends how r u wht r u doing where r u come here its urgent [system43@localhost ~]$ mv -i f3 f1 // interactive mv: overwrite `f1'? n [system43@localhost ~]$ mv -f f3 f1 // force [system43@localhost ~]$ ls dir1 d2 dir2 f1 f2 f3 [system43@localhost ~]$ mv dir1/f1 dir2 [system43@localhost ~]$ ls dir2 dir1 f1 file1 [system43@localhost ~]$ mv dir1/f* dir2 [system43@localhost ~]$ ls dir2 dir1 f1 f2 f3 file1 [system43@localhost ~]$ Link command (ln) Description :It receives either a file or a directory as input, and its output is an updated directory.(or) It make link between files Syntax: ln options source destination ln [OPTION]... [-T] TARGET LINK_NAME (1st form) ln [OPTION]... TARGET (2nd form) ln [OPTION]... TARGET... DIRECTORY (3rd form) ln [OPTION]... -t DIRECTORY TARGET... (4th form) Desc: In the 1st form, create a link to TARGET with the name LINK_NAME. 13

P.N.V.SUNIL KUMAR

In the 2nd form, create a link to TARGET in the current directory. In the 3rd and 4th forms, create links to each TARGET in DIRECTORY. Options: -s symbolic -i interactive prompt -f force Examples: [system43@localhost ~]$ ls dir1 d2 dir2 [system43@localhost ~]$ ln mytable dir1 [system43@localhost ~]$ ls dir1 d2 dir2 mytable [system43@localhost ~]$ ln -i week12.c dir1 ln: replace `dir1/week12.c'? y [system43@localhost ~]$ Remove command (rm) Description: It removes an entry from a directory by destroying its link to the file. (or) It removes a file or directories . To remove the file we must have the write permission. Syntax: rm options filename Options: -f force -i interactive -r recursive, remove directories and their contents recursively -v verbose explain what is being done Examples: [system43@localhost ~]$ rm dd [system43@localhost ~]$ mkdir dir3 [system43@localhost ~]$ rm -r dir3 [system43@localhost ~]$ rm k* // wild card remove ,it removes files starting with k [system43@localhost ~]$ ls 9a.sh b dir2 f1 file3 saras week11a.c week4a.awk [system43@localhost ~]$ Description: find command search for files in a directory hierarchy Syntax: find options pathname criteria action It has no options. Its first argument is the path that we want to search, usually from our home directory. The second argument is the criterion that find needs to complete its search . Pathname: specifies in which directory / all file system . denotes present working directory .. changing the directory Action: is performed on a selected file. print ls execute some commands (exec) when we use ok instead of exec it asks for the conformation . 3 operations in find command ! negate -a and -o or Examples: (1) List out the files with an extension .c 14

Find command (find)

P.N.V.SUNIL KUMAR

[system43@localhost ~]$ find . -name "*.c" -ls 864480 4 -rw-rw-r-- 1 system43 system43 725 Oct 29 12:34 ./week11a.c 864436 4 -rw-rw-r-- 2 system43 system43 448 Oct 27 16:07 ./week12.c 864481 4 -rw-rw-r-- 1 system43 system43 724 Oct 29 12:27 ./week11b.c 864447 4 -rw-rw-r-- 1 system43 system43 87 Nov 6 14:24 ./ex.c [system43@localhost ~]$ find . -name "*.c" -print ./week11a.c ./dir1/week12.c ./week12.c (2)List out the files that that has modified between more than 2 days and less than 5 days -mtime modify time -atime access time [system43@localhost ~]$ find . -mtime +2 -a -mtime -5 ./file3 ./dir2/file3 ./dir2/file1 ./dir2/dir1 [system43@localhost ~]$ find . -atime -2 print // accessed less than 2 days . ./sortex1 ./dir2 ./dir2/kk ./dir2/dir1 (3) List out the files other than c extension [system43@localhost ~]$ find . ! -name "*.c" -ls 864011 4 drwx------ 7 system43 system43 4096 Nov 7 12:01 . 864454 4 -rw-rw-r-- 1 system43 system43 56 Oct 29 10:49 ./dd.awk (4) Remove the files from the current directory with an extension .dat [system43@localhost ~]$ find . -name "*.dat" -exec rm {} \; [system43@localhost ~]$ find . -name "*.dat" -ok rm {} \; (5)Print the files that have the permission 644 [system43@localhost ~]$ find . -perm 664 -print ./week11a.c ./dd.awk ./file3 ./week4a.awk (6)Remove all the Directory files [system43@localhost ~]$ find . -type d -exec rm {} \; SOME OTHER FILTER COMMANDS Description: It copies a specified number of lines from the beginning of one or more files to the standard output . By default it Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. Syntax: head option files Options: -N N lines from starting -r out put in reverse order -c prints first n bytes of each line -v verbose Examples: [system43@localhost ~]$ head file1 // Prints first 10 lines [system43@localhost ~]$ head -3 file1 15

Head command(head)

P.N.V.SUNIL KUMAR

hello hi how r u [system43@localhost ~]$ head -3v file1 ==> file1 <== hello hi how r u [system43@localhost ~]$ head -c7 file1 // print first 7 bytes of file1 hello h[system43@localhost ~]$ Tail command (tail) Description: It output the last part of the line. Syntax: tail option inputfile Options: +N skip N-1 lines -N output last N lines -c output last n bytes -v verbose , always output headers giving file names Examples: [system43@localhost ~]$ tail file1 [system43@localhost ~]$ tail -3 file1 how is u r life going on when r u coming when r u going to die [system43@localhost ~]$ tail -v file1 ==> file1 <== hello hi how r u wht r u doing Description: cut - remove sections from each line of files (or) To extract one or more columns of data from either standard input or from one or more files. Syntax: cut options file-list Options: -b select only these byte -c select only these characters -d use DELIM instead of TAB for field delimiter only on fields -f select only these fields Examples: [system43@localhost ~]$ cut -c1-4 f1 hell u wh wher come [system43@localhost ~]$ cut -b 3 file1 l u d [system43@localhost ~]$ cut -f3 -d " " f1 how r u its 16

Cut command (cut)

P.N.V.SUNIL KUMAR

Paste command (paste)

Description: It combines lines together. It gets its input form two or more files. It treats each line of each file as a column. Syntax: paste option files Options: -d delimiters, reuse characters from LIST instead of TABs -s serial , paste one file at a time instead of in parallel Examples: [system43@localhost ~]$ paste f1 f2 hello friends how r this is my system u wht r u doing where i will do unix programs where r u so please take come here its urgent another system [system43@localhost ~]$ paste -d " |" f1 f2 hello| friends| how| r this| is| my| system u |wht| r| u |doing where |i |will |do| unix| programs where| r| u so| please |take come |here| its |urgent another |system [system43@localhost ~]$ paste -s " |" f1 f2 // serial paste paste: |: No such file or directory hello| friends| how| r u |wht| r| u |doing where| r| u come |here| its |urgent this| is| my| system where |i |will |do| unix| programs so| please |take another |system Description: It sorts the lines in ascending order in a file. Syntax: sort options file Options: -b ignore-leading-blanks -d dictionary-order, consider only blanks and alphanumeric characters -f ignore-case, fold lower case to upper case characters -g general-numeric-sort, compare according to general numerical value -i ignore-nonprinting, consider only printable characters -n numeric-sort, compare according to string numerical value -r reverse the result of comparisons -m merge already sorted files -o write result to file instead of standard output -u unique keys Examples: [system43@localhost ~]$ sort sortex2 are study well where you [system43@localhost ~]$ sort -r sortex2 you where well study are

Sorting command (sort)

P.N.V.SUNIL KUMAR

17

SORT BY FIELDS The UNIX sort defines a filed as a set of characters delimited by a single blank or tab. In addition sort number the fields in a line. The first filed is numbered as 1,the second is numbered as 2 and so on. When a filed sort is required, we need to define which filed or fields are to be used for the sort. Format: +number1 number2 number1 specifies the number of fields to be skipped to get to the beginning of the sort field. Number2 specifies the number of fields to be skipped, relative to the beginning of the line, to get the end of the sort key, EX: +2 -4 field1 field2 field3 field4 fileld5 // indicates take 3&4 fields +3 field1 field2 field3 field4 fileld5 -c verifies that the filed is sorted. If it is not sorted, the first out-of-sequence line is displayed. [system43@localhost ~]$ sort -c sortex2 sort: sortex2:2: disorder: are [system43@localhost ~]$sort +0 -1 sortex1 [system43@localhost ~]$ sort -m sortex1 sortex2 // Merge files come to lab and do hello hi how r u the programs be fast where are Translating character(tr) Description: It replaces each character in a user-specified set of characters with a corresponding character in a second specified set. Syntax: tr options set1 set2 Options: -d delete character -c complement set -s sequence duplicate, replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character -t truncate-set1, first truncate SET1 to length of SET2 Examples: [system43@localhost ~]$ tr "aeiou" "AEIOU" hello hi how r u // input hEllO hI hOw r U // output wht r u doing // input wht r U dOIng // output (ctrl+d) [system43@localhost ~]$ tr -d "aeiou" // delete hello how are you hll hw r y [system43@localhost ~]$ tr "aeiou" "*" // complement hello friends how r u h*ll* fr**nds h*w r *

P.N.V.SUNIL KUMAR

18

Uniq command(uniq)

Count characters, words & lines (wc)

Description: It deletes duplicate lines. To delete the lines must be adjacent. Duplicate lines that are not adjacent are not deleted To delete non adjacent lines the file must be sorted. Syntax: uniq options input-file Options: -c count, prefix lines by the number of occurrences -d repeated, only print duplicate lines -f skip-fields=N, avoid comparing the first N fields -i ignore-case, ignore differences in case when comparing -s skip-chars=N, avoid comparing the first N characters -u unique, only print unique lines Examples: [system43@localhost ~]$ cat >uniqex hello friends how are you wht r u doing hello friends how are you we will discuss about duplicate lines we will discuss about duplicate lines [system43@localhost ~]$ uniq uniqex hello friends how are you wht r u doing hello friends how are you we will discuss about duplicate lines [system43@localhost ~]$ uniq -c uniqex 1 hello friends how are you 1 wht r u doing 1 hello friends how are you 2 we will discuss about duplicate lines [system43@localhost ~]$ sort uniqex > uniqex1 [system43@localhost ~]$ uniq -c uniqex1 2 hello friends how are you 2 we will discuss about duplicate lines 1 wht r u doing [system43@localhost ~]$ uniq -d uniqex1 hello friends how are you we will discuss about duplicate lines Description: It counts the number of characters, words and lines in one or more documents. The character count include newlines(/n). Syntax: wc option file-names Options: -c character count -w word count -l line count Examples: u doing[system43@localhost ~]$ wc file1 2 10 38 file1 [system43@localhost ~]$ wc file1 file2 2 10 38 file1 16 76 386 file2 18 86 424 total [system43@localhost ~]$ wc -c file1 38 file1 [system43@localhost ~]$ wc -l file1 2 file1 19

P.N.V.SUNIL KUMAR

COMPARING FILES cmp, diff and comm. Compare Description: It examines two files byte by byte. The action is taken depends on the (cmp)command options code used. Syntax: cmp options file1 file2 Options: -l Print the byte number (decimal) and the differing byte values (octal) for each difference. -s Print nothing for differing files; return exit status only. Examples: [system43@localhost ~]$ cat > file1 hello how r u wht r u doing [system43@localhost ~]$ cat > file2 hello i am fine wht abouot u [system43@localhost ~]$ cmp file1 file2 file1 file2 differ: byte 7, line 1 [system43@localhost ~]$ cmp -s file1 file2 [system43@localhost ~]$ echo $? 1 [system43@localhost ~]$ cmp -l file1 file2 7 150 151 8 151 40 9 40 141 10 150 155 11 157 40 12 167 146 Difference (diff) command Description: It shows the line-by-line difference between two files. The first file is compared to the second file. The difference are identified such that the first file could be modified to make it match the second file. Syntax: diff options file1 file2 Options : -a Treat all files as text and compare them line-by-line, even if they do not seem to be text. -b Ignore changes in amount of white space. -B Ignore changes that just insert or delete blank lines. -c Use the context output format. -i Ignore changes in case Here the output can be reported in three ways (1) change(c) : Indicates what action should be taken to make file1 the same as file2.Note that a change is a delete and replace. (2) Append (a): Indicates which lines need to be added to file1 to make it the same as file2. Append can take place only at the end of file1; they occur only when file1 is shorter than file2 (3)Delete(d): Indicates what lines must be deleted from file1 to make it the same as file2. Delete can occur only if file1 is longer than file2. Examples: [system43@localhost ~]$ diff file1 file2 1,2c1,2 < hello hi how r u P.N.V.SUNIL KUMAR 20

< wht r u doing // change first and second lines of file1 with file2 --> hello i am fine > wht about u [system43@localhost ~]$ Common (comm) command Description: It compare two files line by line and display the result in three columns. The left column contains unique lines in file1 The center column contains unique lines in file2 The right column contains lines found in both the files. Syntax: comm. options file1 file2 Options: -1 suppress lines unique to FILE1 -2 suppress lines unique to FILE2 -3 suppress lines that appear in both files Examples: [system43@localhost ~]$ cat > f1 aaa bbb ccc ddd eee fff ghi [system43@localhost ~]$ cat > f2 aaa bbb ccc eee ddd fff klmn [system43@localhost ~]$ comm f1 f2 aaa bbb ccc ddd eee fff eee ddd fff ghi klmn [system43@localhost ~]$ Remote Access Description : The main task of telnet is to provide remote services for users. It is a standard Internet protocol and enables connection to a remote system so that the local terminal appears to be a terminal at the remote system site. To connect to the remote system we enter the telnet command and the domain name are IP address Example: telnet 192.168.1.24 Fedora Core release 5 (Bordeaux) Kernel 2.6.15-1.2054_FC5smp on an i686 login: system43 Password: Last login: Fri Nov 13 15:45:19 from 192.168.1.42 [system43@localhost ~]$ Description: It is a TCP/IP standard for copying a file from one computer to another. It differs from other client-server applications Establishing ftp connection To Establishing ftp connection , we enter the ftp command with the remote system domain name on the prompt line after the connection has been made, the local system displays the ftp prompt and waits for the command [system43@localhost ~]$ ftp 21

Terminal Network (telnet) Utility

File transfer protocol (ftp) command

P.N.V.SUNIL KUMAR

ftp> closing an ftp connection At the end of the session, we must close the connection. The connection can be closed in two ways; ftp> quit 221 goodbye $ Close ftp session ftp>close 221 goodbye ftp> for transferring files we use the commands like get , put etc

JOB CONTROLS A Job is a user task that run on a computer. In UNIX a job is a command or set of commands entered on one command line Ex: $ls $ls | lpr are both jobs FOREGROUND JOBS: It is a job run under the active supervision of the user. It is started by the user and many interact with the user though standard input and output. While it is running no other jobs may be started. To start a foreground job we simply enter and key return. i.e all command that we run till now are under foreground. To suspend a foreground job we use ctrl+z. Suspending ,Restarting and Terminating a Foreground Job [system43@localhost ~]$ cat > fgex hello hi how r u wht r u doing [1]+ Stopped cat >fgex // Foreground job suspended [system43@localhost ~]$ cat > fr2example this is an example of foreground commands [2]+ Stopped cat >fr2example // Foreground job suspended [system43@localhost ~]$ ps // job status here we can see two cat commands are working PID TTY TIME CMD 3055 pts/2 00:00:00 bash 3079 pts/2 00:00:00 cat 3085 pts/2 00:00:00 cat 3090 pts/2 00:00:00 ps [system43@localhost ~]$ fg // to resume we need to use fg command, in the file fr2example we can see the explanation why we got fr2example instead of fgex cat >fr2example last stopped command will be resumed first so fr2eample is resumed instead of fgex when we terminate this the fgex will be resumed [system43@localhost ~]$ fg // To cancle job press ctrl+c cat >fgex to cancle press ctrl+c [system43@localhost ~]$ BACKGROUND JOB: When we know a job will take a long time, we may want to run it in the background. Jobs run in the background free the keyboard and monitor so that we may use them for other tasks like editing files and sending files. Starting a Background Job: To start a job in the background we need to use the ampersand(&) immediately after the last argument. There can be no space between the end of the command and the ampersand. P.N.V.SUNIL KUMAR 22

[system43@localhost ~]$ ls& [1] 3174 The number in the brackets([1]) is the job number and the number on the right is the process Identifier. Suspending, Restarting and Terminating a Background Job: To suspend a background job, we use the stop command. To restart it, we use the bg command. To Terminate it we use the kill command. All this three commands required a job number , prefaced with a percent sign(%) . [system43@localhost ~]$ who|more& // starting a background job [2] 3197 [system43@localhost ~]$ stop %2 // suspending [2]+ Stopped who | more [system43@localhost ~]$ bg %3 // to restart [2]+ who | more & [system43@localhost ~]$ kill %2 // Terminated [2] Terminated who | more MOVING BETWEEN BACKGROUND AND FOREGROUND [system43@localhost ~]$ f1 | lpr // start long run job in foreground. ^z [1]+ Stopped f1 | lpr [system43@localhost ~]$ bg [1]+ f1 | lpr & [system43@localhost ~]$ fg %1 f1|more [system43@localhost ~]$

// suspended the job(ctrl+z) // Moving job to background // Bring active job to foreground // job running in fg

ALIASES An alias provides a means of creating customized commands by assigning a name to a command. Aliases are handled differently in each shell. Aliases in Korn and Bash shells Here the alias is created using the alias command. Format: alias name=command-defination [system43@localhost ~]$ alias dir=ls // using alias to rename the list command [system43@localhost ~]$ dir dir1 dir2 f1 f2 fgex file1 file2 fr2 fr2example [system43@localhost ~]$ alias long='ls -l' // alias of command with options [system43@localhost ~]$ long total 32 drwxrwxr-x 4 system43 system43 4096 Nov 6 14:39 dir1 drwxrwxr-x 3 system43 system43 4096 Nov 6 13:04 dir2 -rw-rw-r-- 1 system43 system43 53 Nov 18 13:55 f1 -rw-rw-r-- 1 system43 system43 29 Nov 13 15:59 f2 [system43@localhost ~]$ alias // listing all the alias alias dir='ls' alias long='ls -l' alias vi='vim' [system43@localhost ~]$ dir f* // Arguments to alias commands f1 f2 fgex file1 file2 fr2 fr2example Aliases in the C shell C shell aliases differ from Korn shell aliases in format but not in function. They also have a powerful set of features, especially for argument definition.. Syntax: alias name definition P.N.V.SUNIL KUMAR 23

Arguments of Alias Commands: Designator Meaning \!* Position of the only arguments. \!^ Position of the first arguments \!$ Position of the last arguments \!:n Position of the nth arguments To remove an alias in CSH us the command unalias name To list out all the aliases specify the name alias CHANGING PERMISSIONS When a directory or file is created, the system automatically assigns default permissions. The owner of the directory or file can change them. To change the permissions, we use the chmod command Syntax: chmod options mode file/directory Options: -r recursive Mode : symbolic or octal Symbolic mode: when we use this mode we tell UNIX what permissions we want to set. There are 3 set of operators. To assign absolute permissions to a set, = in this case the current permissions for a set are replaced by the new permissions. + to add permissions to remove one or two permissions and leave the other alone, [system43@localhost ~]$ ls -l f1 -rw-rw-r-- 1 system43 system43 21 Nov 26 14:05 f1 [system43@localhost ~]$ chmod u=rwx,g-w,o+w f1 [system43@localhost ~]$ ls -l f1 -rwxr--rw- 1 system43 system43 21 Nov 26 14:05 f1 The use of symbolic code in the chmod command allows a user to set, add or remove individual permissions. Octal mode: A faster way to enter permissions is to use the octal equivalent of the codes. Here all the permissions codes are changed. It is not like symbolic modes where you need to specify only what you want to change. With octal codes, you must completely represent all the user codes each time. Permission octal values user group others r w x r w x r w x 4 2 1 4 2 1 4 2 1 [system43@localhost ~]$ ls -l f2 -rw-rw-r-- 1 system43 system43 110 Dec 10 10:40 f2 [system43@localhost ~]$ chmod 777 f2 [system43@localhost ~]$ ls -l f2 -rwxrwxrwx 1 system43 system43 110 Dec 10 10:40 f2 [system43@localhost ~]$ chmod 764 f1 [system43@localhost ~]$ ls -l f1 -rwxrw-r-- 1 system43 system43 21 Nov 26 14:05 f1 [system43@localhost ~]$ Note: default permission for Directory is 777 default permission for Files is 666 Mask is used to create the default permissions . The use of octal code in the chmod command requires that all permissions be completely reset; a user cannot add or remove individual settings.

P.N.V.SUNIL KUMAR

24

VI EDITOR The commands in Vi are divided in to three separate categories Local Commands are applied to the text at the current cursor location. Range Commands applied to blocks of text are known as text Commands Global Commands are applied to all of the text in the whole buffer. Local Commands i I a A o O r R x X J Range Commands Character h l lines 0 ,$ -, + k, j Word b w e Screen H,L,M File G dd dh yy p Global Commands Ctrl + y Ctrl + e Ctrl + u Ctrl + d Ctrl + b Ctrl + f Save and Exit commands of ex mode :w :x :wq :q!

Insert Text before the current character Insert Text at the beginning of the current line Appends Text to right of cursor(Existing test shifted right) Append Text to the end of line. Opens(insert) a line below the current line Opens (insert ) a line above the current line Replace the current character at the cursor with then new one. Replaces a set of character with the new set of characters. Deletes the current character Deletes the character before the cursor. Join two lines. Move to previous character. 4h move 4 character backward Move to next character (forward) 2l move 2 characters forward. Beginning and end of current line, respectively Beginning of line above (-) and line below(+), respectively Move to one line above (k) and below(j) from the current position Beginning of word backward Beginning of next word forward End of word forward. Beginning of top, bottom, or middle line , respectively. Beginning of last line in a file. Delete current line Delete previous character. Yank(copies) current line. Put after current line (paste) Scrolls up one line Scrolls down one line Scrolls up half a screen Scrolls down half a screen Scrolls up whole screen Scrolls down whole screen

Save file and remains in editing mode Saves file and quits editing mode Saves file and quits editing mode Quits editing mode after abandoning changes

P.N.V.SUNIL KUMAR

25

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 real reason why the C Shell is so popular is that it is usually selected as the default login shell for most users. The features that guarantee its continued use in this arena are aliases, and history lists. There are rumours 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.

P.N.V.SUNIL KUMAR

26

WEEK1 Session-1 a)Log into the system b)Use vi editor to create a file called myfile.txt which contains some text. c)correct typing errors during creation. d)Save the file e)logout of the system [root@localhost sunil]# vi myfile.txt

[root@localhost sunil] exit

P.N.V.SUNIL KUMAR

27

Session-2 a)Log into the system b)open the file created in session 1 c)Add some text d)Change some text e)Delete some text f)Save the Changes g)Logout of the system [root@localhost sunil]# vi myfile.txt

(Add and change the text)

(Delete some text) P.N.V.SUNIL KUMAR 28

( Save the changes)

P.N.V.SUNIL KUMAR

29

Week2 a)Log into the system Fedora Core release 5 (Bordeaux) Kernel 2.6.15-1.2054_FC5smp on an i686 login: root Password: Last login: Fri Oct 30 14:58:32 from 192.168.1.42 [root@localhost sunil]# b)Use the cat command to create a file containing the following data. Call it mytable use tabs to separate the fields. 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 [root@localhost sunil]# cat > mytable 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 c)Use the cat command to display the file, mytable. [root@localhost sunil]# cat mytable 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 d)Use the vi command to correct any errors in the file, mytable. [root@localhost sunil]# vi mytable 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 :wq [root@localhost sunil]# e)Use the sort command to sort the file mytable according to the first field. Call the sorted file my table (same name) f)Print the file mytable g)Use the cut and paste commands to swap fields 2 and 3 of mytable. Call it my table (same name) [root@localhost sunil]# cut -f 2 mytable > cutlist1 [root@localhost sunil]# cat cutlist1 Ravi Ramu Sita Raju [root@localhost sunil]# cut -f 1,3 mytable > cutlist2 [root@localhost sunil]# cat cutlist2 1425 15.65 4320 26.27 6830 36.15 1450 21.86 [root@localhost sunil]# paste cutlist2 cutlist1 > mytable

P.N.V.SUNIL KUMAR

30

h)Print the new file, mytable [root@localhost sunil]# cat mytable 1425 15.65 Ravi 4320 26.27 Ramu 6830 36.15 Sita 1450 21.86 Raju i)Logout of the system. [root@localhost sunil]# logout

P.N.V.SUNIL KUMAR

31

Week 3 1) a)Login to the system Fedora Core release 5 (Bordeaux) Kernel 2.6.15-1.2054_FC5smp on an i686 login: root Password: Last login: Fri Oct 30 14:58:32 from 192.168.1.42 [root@localhost sunil]# b)Use the appropriate command to determine your login shell [root@localhost sunil]# ps PID TTY 2893 pts/0 3081 pts/0 TIME CMD 00:00:00 bash 00:00:00 ps

c)Use the /etc/passwd file to verify the result of step b. [root@localhost sunil]# cat /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin news:x:9:13:news:/etc/news: uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin games:x:12:100:games:/usr/games:/sbin/nologin gopher:x:13:30:gopher:/var/gopher:/sbin/nologin sunil:x:500:500:sunil:/home/sunil:/bin/bash system58:x:558:558:system58:/home/system58:/bin/bash system59:x:559:559:system59:/home/system59:/bin/bash system60:x:560:560:system60:/home/system60:/bin/bash d)Use the who command and redirect the result to a file called myfile1. Use the more command to see the contents of myfile1. [root@localhost sunil]# who > myfile1 [root@localhost sunil]# cat myfile1 root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin

P.N.V.SUNIL KUMAR

32

e)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. [root@localhost sunil]# who > myfile2 | date Mon May 26 11:02:51 IST 2008 [root@localhost sunil]# cat myfile2 root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin Week 3 (2) [root@localhost sunil]# cat file1 hello friends hi how r u what are you doing

a) Write a sed command that deletes the first character in each line in a file [root@localhost sunil]# sed e 's/^.//g' file1 ello friends hi ow r u hat are u doing b) Write a sed command that deletes the character before the last character in each line in a file. [root@localhost sunil]# sed e 's/\(.\)\(.\)$/\2/' file1 hello friends i how ru what are u doig c) Write a sed command that swaps the first and second words in each line in a file. [root@localhost root]# sed -e 's/\([a-z]* \)\([a-z]* \)/\2 \1/' file1 friends hello hi r how u are what u doing

P.N.V.SUNIL KUMAR

33

Week 4a Pipe your /etc/passwd file to awk, and print out the home directory of each user. BEGIN{ FS=":" while("cat /etc/passwd" | getline) { print($1 "\t" $6) } } [root@localhost sunil]#awk f week4a.awk root /root bin /bin daemon /sbin adm /var/adm lp /var/spool/lpd sync /sbin shutdown /sbin halt /sbin mail /var/spool/mail news /etc/news uucp /var/spool/uucp operator /root games /usr/games gopher /var/gopher ftp /var/ftp nobody / dbus / rpm /var/lib/rpm apache /var/www distcache / ntp /etc/ntp nscd / vcsa /dev system10 /home/system10 system11 /home/system11 system12 /home/system12 system13 /home/system13 system14 /home/system14 system15 /home/system15 system16 /home/system16 system17 /home/system17 system18 /home/system18 system19 /home/system19 system20 /home/system20 OR [root@localhost sunil]# cat /etc/passwd | awk '{ print $1 }' root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin P.N.V.SUNIL KUMAR 34

daemon:x:2:2:daemon:/sbin:/sbin/nologin nut:x:57:57:Network ldap:x:55:55:LDAP mysql:x:27:27:MySQL ident:x:98:98:pident postfix:x:89:89::/var/spool/postfix:/sbin/nologin mailman:x:41:41:GNU week4b b)Develop an interactive grep script that asks for a word and a file name and then tells how many lines contain that word. c)Repeat d)Part using awk b) [root@localhost sunil]# grep -c "hi" file3 3 d) [root@localhost sunil]# grep -c "hai" kkk | awk '{ print "The count number is:"$1 }' The count number is:3 OR d) BEGIN{ while(1) { printf("Enter File name and 'quit' to exit:"); getline fn if(fn=="quit") { exit } printf("\nEnter the search String:") getline s printf("\n Actual command is\n") X="grep -c " s " " fn print X X | getline printf("\nTotal no.of %s present is %d\n",s,$0) } } [root@localhost sunil]# awk -f week4b.awk Enter File name and 'quit' to exit:file3 Enter the search String:hi Actual command is grep -c hi kkk Total no.of hi present is 3 Enter File name and 'quit' to exit:quit [root@localhost sunil]# cat file3 Hi Hello Hi Hi P.N.V.SUNIL KUMAR 35

Week 5a Write a shell script that takes a command line argument and reports on whether it is directory, a file, or something else. clear echo "Entered file name is :$1" if [ -f $1 ] then echo "You entered filename" cat $1 elif [ -d $1 ] then echo "You entered a directory name " ls $1 else echo "You entered invalid filename" fi input/output: [root@localhost sunil]# sh week5a.sh file1 Entered file name is :file1 You entered filename hai how r u . Week 5b 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. Clear echo "Enter the file name with path" read fname1 echo "Enter the new file name" read fname2 tr '[a-z]' '[A-Z]' < $fname1 > $fname2 echo " The data is converted into upper case " cat $fname2 echo "The file exist in current directory" ls input/output: [root@localhost sunil]# sh week5b.sh Enter the file name with path sunil/kkk Enter the new file name kkk The data is converted into upper case HAI HOW R U WHAT R U DOING IN IT The file exist in current directory 5a cutlist2 whofile sunilfile myfile newfile userlogin.sh week2 week5a (copy).sh week7b.sh 36

P.N.V.SUNIL KUMAR

5aoutput fileper.sh sunilmyfile myfile1 passwd.bak vifile a.out fingerfile kkk myfile2 rubyone week10.c Week 5c

week32a week5a.sh week32b week5b.sh

week8a.sh week8b.sh

Write a shell script that determines the period for which a specified user is working on the system echo "Enter the username" read user who -T | grep $user > /dev/null if [ $? -eq 0 ] then echo "The user is logged in" var=` who -T | grep $user ` set $var echo "The logged user is: $1" echo "The user login time is :$5" else echo "The user is not logged in" fi Input/Output: [root@localhost sunil]# sh week5c.sh Enter the username System8 The logged user is : system8 The user login user time is: 11:51

P.N.V.SUNIL KUMAR

37

Week 6a 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. echo "Enter the file name" read filename echo "Enter the starting line number" read s echo "Enter the ending line number" read n sed -n $s,$n\p $filename | cat >newfile cat newfile Input/Output: [root@localhost sunil]# sh week6a.sh Enter the file name Mytable Enter the starting line number 1 Enter the ending line number 3 1425 15.65 Ravi 4320 26.27 Ramu 6830 36.15 Sita Week 6b Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. echo "U entered file name is $1" echo "Enter the word to delete from the file " read word sed /$word/d $1 Input/Output: [root@localhost sunil]# sh week6b.sh mytable U entered file name is mytable Enter the word to delete from the file Ravi 4320 26.27 Ramu 6830 36.15 Sita 1450 21.86 Raju

P.N.V.SUNIL KUMAR

38

Week 7a 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 Basic salary is <>=1500 then HRA = Rs500 and DA=98%of the basic. The basic salary is entered interactively through the key board echo "Enter the employee name" read ename echo "Enter the employee designation" read desig echo "Enter the basic salary of the employee" read bsal if [ $bsal -lt 1500 ] then hra=$(echo "scale=2;($bsal * (10/100))" | bc -l) da=$(echo "scale=2;($bsal * (90/100))" | bc -l) nsal=$(echo "scale=2;($bsal + $hra + $da)"| bc -l) elif [ $bsal -ge 1500 ] then da=$(echo "scale=2;($bsal * (98/100)" | bc -l) nsal=$(echo "scale=2;(500+$da+$bsal)"|bc -l) fi echo "The name of the employee :"$ename echo "The designation of the employee :"$desig echo "The HRA of the employee is:"$hra echo "The DA of the employee is :"$da echo "The Net salary of the employee:"$nsal

Input/Output: [root@localhost sunil]# sh week7a.sh Enter the employee name ABC Enter the employee designation XYZ Enter the basic salary of the employee 1500 (standard_in) 2: parse error (standard_in) 1: parse error The name of the employee :ABC The designation of the employee :XYZ The HRA of the employee is: The DA of the employee is : The Net salary of the employee: [root@localhost sunil]# vi week7a.sh [root@localhost sunil]# sh week7a.sh Enter the employee name abc Enter the employee designation xyz Enter the basic salary of the employee P.N.V.SUNIL KUMAR 39

1200 The name of the employee :abc The designation of the employee :xyz The HRA of the employee is:120.00 The DA of the employee is :1080.00 The Net salary of the employee:2400.00 Week 7b Write a shell script that accepts two integers as its arguments and compute the value of first number raised to the power of the second number. echo "Enter the first number" read number echo "Enter the power number" read power i=1 prod=1 while [ $i -le $power ] do prod=`echo $prod \* $number|bc` i=` expr $i + 1 ` done echo "The resut is : "$prod Input/Output: [root@localhost sunil]# sh week7b.sh Enter the first number 2 Enter the power number 3 The resut is : 8

P.N.V.SUNIL KUMAR

40

Week 8a 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 program ask the user for the necessary information, such as the file name ,new name and soon clear ch='y' while [ $ch = 'y' ] do clear echo "MAIN MENU" echo "1->Coping the files" echo "2->Removing the files" echo "3->Renaming the files" echo "4->Liking the files" echo "Enter your choice" read choice case $choice in 1) echo "Copying the files" echo "Enter the source file" read source echo "Enter the destination file" read destination cp $source $destination echo "The files are copied" ;; 2) echo "Removing the files" echo "Enter the file name to delete or remove" read fname rm $fname echo "The file is removed" ;; 3) echo "Renaming the files" echo "Enter the source file" read old echo "Enter the destination file" read end mv old end echo "The file name is renamed" ;; 4) echo "Linking the files" echo "Enter the name of the linking file" read lname1 echo "Enter the name of the file" read lname2 ln $lname1 $lname2 ;; *) ;; echo "U entered wrong choice"

P.N.V.SUNIL KUMAR

41

esac echo "Do you want to continue(y/n)" read ch done Input/Output: [root@localhost sunil]# sh week8a.sh MAIN MENU 1->Coping the files 2->Removing the files 3->Renaming the files 4->Liking the files Enter your choice 1 Copying the files Enter the source file sunil/kkk Enter the destination file kkk The files are copied Do you want to continue(y/n) n

Week 8b Write a shell script that takes names as command-line argument and reports when that person logs in echo "Enter the login name" read logname echo "The name u enterd is :"$logname finger $logname [root@localhost sunil]# sh week8b.sh Enter the login name sunil The name u enterd is :sunil Login: sunil Name: (null) Directory: /home/sunil Shell: /bin/bash Last login Sat May 17 07:36 (IST) on :0 No mail. No Plan.

P.N.V.SUNIL KUMAR

42

Week 8c Write a shell script which receives two file names as arguments. It should check whether the two file contents are same are not . If they are same then second file should be deleted echo "Enter the first filename" read fname1 echo "Enter the second filename" read fname2 echo "Comparisons of two files" if cmp $fname1 $fname2 then echo "Two files are equal" rm $fname1 else echo "Two files are not equal" fi Input/Output: [root@localhost sunil]# sh week8c.sh Enter the first filename myfile Enter the second filename myfile1 Comparisons of two files myfile myfile1 differ: byte 1, line 1 Two files are not equal

P.N.V.SUNIL KUMAR

43

Week 9a Write a shell script that displays a list of all the files in the current directory to which the user has read, write and execute permissions. echo "Enter the file name" read fname if [ ! -z $fname ] then if [ -r $fname -a -w $fname -a -x $fname ] then echo "The file is having all permissions " elif [ -r $fname -a -w $fname ] then echo "The file permissions are read and write " elif [ -w $fname -a -x $fname ] then echo "The file permissions are write and execute" elif [ -r $fname ] then echo "The file permissions are read only" elif [ -w $fname ] then echo "The file permissions are write only" elif [ -x $fname ] then echo "The file permissions are execute only " else echo "The permissions are denied" fi else echo "Improper file name " fi Input/Output: [root@localhost sunil]# sh week9a.sh Enter the file name myfile2 The file is having all permissions

P.N.V.SUNIL KUMAR

44

Week 9b 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. echo "Enter the word" read word echo "Enter the file name" read fname echo "The number of times occured this word in this file" grep -c $word $fname Input/Output: [root@localhost sunil]# sh week9b.sh Enter the word hai Enter the file name myfile The number of times occurred this word in this file 0 [root@localhost sunil]# cat myfile hi hello

P.N.V.SUNIL KUMAR

45

Week 9c 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. ch='y' while [ $ch == 'y' ] do clear echo "MAIN MENU" echo "1->To find the length of the string " echo "2->To extract the substring from a given string" echo "Enter the string to perform operations" read str echo "Enter your choice " read choice case $choice in 1) echo "U seleted to find the length of the string" echo "The length of the string is : ${#str}" ;; 2) echo " u seleted to extract the substring" echo "Enter the starting position to view the substring" read ch1 echo "Enter the ending position to view the substring" read ch2 echo ${str:ch1:$ch2} ;; *) echo "you r option is incorrect" ;; esac echo "DO U WANT TO CONTINUE(y/n)" read ch done Input/Output: [root@localhost sunil]# sh week9c.sh MAIN MENU 1->To find the length of the string 2->To extract the substring from a given string Enter the string to perform operations GPCET Enter your choice 1 U seleted to find the length of the string The length of the string is : 5 DO U WANT TO CONTINUE(y/n) n

P.N.V.SUNIL KUMAR

46

Week 10 Write a C program that takes one or more directory names as command line input and reports the following information on the file (a) File Type (b) Number of links (c) Read,write and execute permissions (d) Time of last access #include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<fcntl.h> #include<time.h> #include<sys/stat.h> main() { char fname[20]; struct stat buf; printf("Enter the file name\n"); scanf("%s",fname); stat(fname,&buf); printf("Mode word :%d\n",buf.st_mode); printf("Inode no :%d\n",buf.st_ino); printf("No of links :%d\n",buf.st_nlink); printf("size of the file in bytes %d\n",buf.st_size); printf(" User id:%d\n",buf.st_uid); printf("Group id : %d\n",buf.st_gid); printf("Access time : %d\n",buf.st_atime); printf("Modification time : %d\n",buf.st_mtime); printf("Change time : %d\n",buf.st_ctime); } Input/output: [root@localhost sunil]# cc week10.c [root@localhost sunil]# ./a.out Enter the file name myfile Mode word :33261 Inode no :11537 No of links :1 size of the file in bytes 30 User id:543 Group id : 534 Access time : 1256793610 Modification time : 1256640268 Change time : 1256640686

P.N.V.SUNIL KUMAR

47

Week 11 Write a C program that simulates the following unix commands: (a) mv #include<stdio.h> #include<sys/stat.h> #include<fcntl.h> main() { int i; char fname1[20],fname2[20]; printf("ENTER THE SOURCE FILE NAME\n"); scanf("%s",fname1); printf("ENTER THE DESTINATION FILE NAME\n"); scanf("%s",fname2); i=rename(fname1,fname2); if(i==0) printf("THE FILE MOVED\n"); else printf("THE FILE IS NOT MOVED\n"); } Input/Output : [root@localhost sunil]# cc week11a.c [root@localhost sunil]# ./a.out ENTER THE SOURCE FILE NAME myfile ENTER THE DESTINATION FILE NAME sunil/newfile THE FILE MOVED [root@localhost sunil]# cd sunil [root@localhost sunil]# ls kkk newfile [root@localhost sunil]# cc weeklla.c [root@localhost sunil]# ./a.out ENTER THE SOURCE FILE NAME asd ENTER THE DESTINATION FILE NAME mm THE FILE MOVED [root@localhost sunil]# cat asd cat: asd: No such file or directory [system43@localhost sunil]# cat mm hello hi how r u

P.N.V.SUNIL KUMAR

48

Week11b (b) cp #include<fcntl.h> #include<sys/stat.h> #include<stdio.h> #define BUFSIZE 1024 int main(void) { int fd1,fd2; int n; char buf[BUFSIZE],fname1[20],fname2[20]; printf("ENTER THE SOURCE FILE NAME\n"); scanf("%s",fname1); printf("ENTER THE DESTINATION FILE NAME\n"); scanf("%s",fname2); fd1=open(fname1,O_RDONLY); fd2=open(fname2,O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IROTH); while((n=read(fd1,buf,BUFSIZE))>0) write(fd2,buf,n); printf("THE FILE IS COPIED\n"); close(fd1); close(fd2); } Input/Output: [root@localhost sunil]# cc week11b.c [root@localhost sunil]# ./a.out ENTER THE SOURCE FILE NAME myfile1 ENTER THE DESTINATION FILE NAME sunil/newfile1 THE FILE IS COPIED [root@localhost sunil]# cd sunil [root@localhost sunil]# ls kkk newfile newfile1 [root@localhost sunil]# cat newfile1 [root@localhost sunil]# cc week11.c [root@localhost sunil]# ./a.out ENTER THE SOURCE FILE NAME asd ENTER THE DESTINATION FILE NAME mm THE FILE IS COPIED [root@localhost sunil]# cat mm hello hi how r u

S_IWUSR |S_IRGRP |

P.N.V.SUNIL KUMAR

49

Week12 Write a C program that simulates ls command #include<stdio.h> #include<dirent.h> int main(int argc,char **argv) { DIR *dir; struct dirent *direntry; dir=opendir(argv[1]); if(dir==NULL) { printf("The directory is not found please try again "); } else { while((direntry=readdir(dir))!=NULL) printf("%10d %s",direntry->d_ino,direntry->d_name); closedir(dir); } } Input/Output: [root@localhost sunil]# cc week12.c [root@localhost sunil]# ./a.out sunil 864422 . 864433 file2 864432 file1 864011 .. [root@localhost sunil]# ls sunil file1 file2

P.N.V.SUNIL KUMAR

50

Viva Questions & Answers Could you tell something about the Unix System Kernel? The kernel is the heart of the UNIX operating system, its responsible for controlling the computers resources and scheduling user jobs so that each one gets its fair share of resources. How can you tell what shell you are running on UNIX system? You can do the echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with [] What do you mean by u-area (user area) or u-block? This contains the private data that is manipulated only by the Kernel. This is local to the Process, i.e. each process is allocated a u-area. What scheme does the Kernel in Unix System V follow while choosing a swap device among the multiple swap devices? Kernel follows Round Robin scheme choosing a swap device among the multiple swap devices in Unix System V. List the system calls used for process management: System calls fork() exec() wait() [] Description To create a new process To execute a new program in a process

How do you change File Access Permissions? Every file has following attributes: owners user ID ( 16 bit integer ) owners group ID ( 16 bit integer ) File access mode word r w x -r w x- r w x (user permission-group permission-others permission) r-read, w-write, x-execute To change the access mode, we use chmod(filename,mode). Example: To change mode of myfile to rw-rw-r (ie. read, write permission for user - [] Explain the layered aspect of a UNIX system. What are the layers? What does it mean to say they are layers? A UNIX system has essentially three main layers: . The hardware . The operating system kernel . The user-level programs The kernel hides the systems hardware underneath an abstract, high-level programming interface. It is responsible for implementing many of the facilities that users and user-level programs take for P.N.V.SUNIL KUMAR 51

granted. The kernel assembles all of the following UNIX concepts from lower-level [] What is the use of grep command? grep is a pattern search command. It searches for the pattern, specified in the command line with appropriate option, in a file(s). Syntax : grep Example : grep 99mx mcafile What difference between cmp and diff commands? cmp - Compares two files byte by byte and displays the first mismatch diff - tells the changes to be made to make the files identical What is the significance of the tee command? It reads the standard input and sends it to the standard output while redirecting a copy of what it has read to the file specified by the user. Is du a command? If so, what is its use? Yes, it stands for disk usage. With the help of this command you can find the disk capacity and free space of the disk. How to terminate a process which is running and the specialty on command kill 0? With the help of kill command we can terminate the process. Syntax: kill pid Kill 0 - kills all processes in your system except the login shell. Explain kill() and its possible return values. There are four possible results from this call: kill() returns 0. This implies that a process exists with the given PID, and the system would allow you to send signals to it. It is system-dependent whether the process could be a zombie. kill() returns -1, errno == ESRCH either no process exists with the given PID, or [] What does the command $who | sort logfile > newfile do? The input from a pipe can be combined with the input from a file . The trick is to use the special symbol - (a hyphen) for those commands that recognize the hyphen as std input. In the above command the output from who becomes the std input to sort , meanwhile sort opens the file [] What are shell variables? Shell variables are special variables, a name-value pair created and maintained by the shell. Example: PATH, HOME, MAIL and TERM How many prompts are available in a UNIX system? Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt). Is it possible to create new file system in UNIX? P.N.V.SUNIL KUMAR 52

Use su command. The system asks for password and when valid entry is made the user gains super user (admin) privileges. How the Kernel handles the copy on write bit of a page, when the bit is set? In situations like, where the copy on write bit of a page is set and that page is shared by more than one process, the Kernel allocates new page and copies the content to the new page and the other processes retain their references to the old page. After copying the Kernel updates the page []

Difference between the fork() and vfork() system call? During the fork() system call the Kernel makes a copy of the parent processs address space and attaches it to the child process. But the vfork() system call do not makes any copy of the parents address space, so it is faster than the fork() system call. The child process as a result of the vfork() [] How the Kernel handles the fork() system call in traditional Unix and in the System V Unix, while swapping? Kernel in traditional Unix, makes the duplicate copy of the parents address space and attaches it to the childs process, while swapping. Kernel in System V Unix, manipulates the region tables, page table, and pfdata table entries, by incrementing the reference count of the region table of shared regions. What are the requirements for a swapper to work? The swapper works on the highest scheduling priority. Firstly it will look for any sleeping process, if not found then it will look for the ready-to-run process for swapping. But the major requirement for the swapper to work the ready-to-run process must be core-resident for at least 2 seconds before swapping out. And for swapping [] What is Expansion swap? At the time when any process requires more memory than it is currently allocated, the Kernel performs Expansion swap. To do this Kernel reserves enough space in the swap device. Then the address translation mapping is adjusted for the new virtual address space but the physical memory is not allocated. At last Kernel swaps the [] What is Fork swap? fork() is a system call to create a child process. When the parent process calls fork() system call, the child process is created and if there is short of memory then the child process is sent to the read-to-run state in the swap device, and return to the user state without swapping the parent process. [] What are the entities that are swapped out of the main memory while swapping the process out of the main memory? All memory space occupied by the process, processs u-area, and Kernel stack are swapped out, theoretically. Practically, if the processs u-area contains the Address Translation Tables for the process then Kernel implementations do not swap the u-area. Is the Process before and after the swap are the same? Give reason. P.N.V.SUNIL KUMAR 53

Process before swapping is residing in the primary memory in its original form. The regions (text, data and stack) may not be occupied fully by the process, there may be few empty slots in any of the regions and while swapping Kernel do not bother about the empty slots while swapping the process outAfter swapping [] What are the events done by the Kernel after a process is being swapped out from the main memory? When Kernel swaps the process out of the primary memory, it performs the following: Kernel decrements the Reference Count of each region of the process. If the reference count becomes zero, swaps the region out of the main memory. Kernel allocates the space for the swapping process in the swap device. Kernel locks the other swapping process while [] What is major difference between the Historic Unix and the new BSD release of Unix System V in terms of Memory Management? Historic Unix uses Swapping entire process is transferred to the main memory from the swap device, whereas the Unix System V uses Demand Paging only the part of the process is moved to the main memory. Historic Unix uses one Swap Device and Unix System V allow multiple Swap Devices What is an advantage of executing a process in background? The most common reason to put a process in the background is to allow you to do something else interactively without waiting for the process to complete. At the end of the command you add the special background symbol, &. This symbol tells your shell to execute the given command in the background. Example: cp *.* [] What Happens when you execute a program? When you execute a program on your UNIX system, the system creates a special environment for that program. This environment contains everything needed for the system to run the program as if no other program were running on the system. Each process has process context, which is everything that is unique about the state of [] What are the process states in Unix? As a process executes it changes state according to its circumstances. Unix processes have the following states: Running : The process is either running or it is ready to run . Waiting : The process is waiting for an event or for a resource. Stopped : The process has been stopped, usually by receiving a signal. Zombie : The [] What is a zombie? When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the childs exit status. To be able to get this information, the parent calls `wait(); In the []

P.N.V.SUNIL KUMAR

54

How can a parent and child process communicate? A parent and child can communicate through any of the normal inter-process communication schemes (pipes, sockets, message queues, shared memory), but also have some special ways to communicate that take advantage of their relationship as a parent and child. One of the most obvious is that the parent can get the exit status of the [] How can you get/set an environment variable from a program? Getting the value of an environment variable is done by using `getenv(). Setting the value of an environment variable is done by using `putenv(). Explain fork() system call. The `fork() used to create a new process from an existing process. The new process is called the child process, and the existing process is called the parent. We can tell which is which by checking the return value from `fork(). The parent gets the childs pid returned to him, but [] What are various IDs associated with a process? Unix identifies each process with a unique integer called ProcessID. The process that executes the request for creation of a process is called the parent process whose PID is Parent Process ID. Every process is associated with a particular user called the owner who has privileges over the process. The identification for the user is [] Brief about the initial process sequence while the system boots up. While booting, special process called the swapper or scheduler is created with Process-ID 0. The swapper manages memory allocation for processes and influences CPU allocation. The swapper inturn creates 3 children: the process dispatcher,vhand and dbflush with IDs 1,2 and 3 respectively. This is done by executing the file /etc/init. Process dispatcher gives birth to the shell. [] What is a shell? A shell is an interactive user interface to an operating system services that allows an user to enter commands as character strings or through a graphical user interface. The shell converts them to system calls to the OS or forks off a process to execute the command. System call results and other information from the OS [] How does the inode map to data block of a file? Inode has 13 block addresses. The first 10 are direct block addresses of the first 10 data blocks in the file. The 11th address points to a one-level index block. The 12th address points to a two-level (double in-direction) index block. The 13th address points to a three-level(triple in-direction)index block. This provides a very large maximum [] Discuss the mount and unmount system calls The privileged mount system call is used to attach a file system to a directory of another file system; the unmount system call detaches a file system. When you mount another file system on to your directory, you are essentially splicing one directory tree onto a branch in another directory tree. The first argument to [] P.N.V.SUNIL KUMAR 55

How do you create special files like named pipes and device files? The system call mknod creates special files in the following sequence. 1. kernel assigns new inode, 2. sets the file type to indicate that the file is a pipe, directory or special file, 3. If it is a device file, it makes the other entries like major, minor device numbers. For example: If the device is a disk, major [] What are links and symbolic links in UNIX file system? A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers. Symbolic link is a file that only contains the name of another file.Operation [] What are the Unix system calls for I/O? open(pathname,flag,mode) - open file creat(pathname,mode) - create file close(filedes) - close an open file read(filedes,buffer,bytes) - read data from an open file write(filedes,buffer,bytes) - write data to an open file lseek(filedes,offset,from) - position an open file dup(filedes) - duplicate an existing file descriptor dup2(oldfd,newfd) - duplicate to a desired file descriptor fcntl(filedes,cmd,arg) - change properties of an open file ioctl(filedes,request,arg) - change the behaviour [] What is a FIFO? FIFO are otherwise called as named pipes. FIFO (first-in-first-out) is a special file which is said to be data transient. Once data is read from named pipe, it cannot be read again. Also, data can be read only in the order written. It is used in interprocess communication where a process writes to one end of [] What is inode? All UNIX files have its description stored in a structure called inode. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers [] How are devices represented in UNIX? All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A regular file is just an ordinary data file in the disk. A block special file represents a device with characteristics similar to a disk (data transfer [] Brief about the directory representation in UNIX A Unix directory is a file containing a correspondence between filenames and inodes. A directory is a special file that the kernel maintains. Only kernel modifies directories, but processes can read P.N.V.SUNIL KUMAR 56

directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries [] What is inode? All UNIX files have its description stored in a structure called inode. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers [] How are devices represented in UNIX? All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A regular file is just an ordinary data file in the disk. A block special file represents a device with characteristics similar to a disk (data transfer []
How is the command $cat file2 different from $cat >file2 The Commond $cat file in unix is used to display the content of the file and where as commond $cat >> file is to append the text to the end of the file without overwritting the information of the file. Incase if the file does not exist in the directory the commond will create a newfile in file system.

Answer

$cat >file means to create a new file $cat file means to open an existing file.
Answered By: selva,ravi Date: 7/13/2007

cat > file it means creating file for file cat file it means used to display the file content

Explain the steps that a shell follows while processing a command. When processing a command the searchs for the utility for the command in the directories specified in the PATH varible and it in invokes that utility. That utility will execute the command with help of kernel and the output is given to shell. And then the displays out put to the user.

Answer

Explain the steps that a shell follows while processing a command. When processing a command the searchs for the utility for the command in the directories specified in the PATH varible and it in invokes that utility. That utility will execute the command with help of kernel and the output is given to shell. And then the displays out put to the user.

Answer

P.N.V.SUNIL KUMAR

57

Which command is used to delete all files in the current directory and all its sub-directories?

#rm -fr <Directory name> # rm -rf * Answer


Answered By: Amit Shiknis Date: 12/25/2007

rm -r *

What is the use of the command "ls -x chapter[1-5]"

Answer How does the kernel differentiate device files and ordinary files?

Yes you are correct. It stands for listing the files Chapter with suffix 1 to 5 but it will display the files in columns as with-x option.

Device filles are of 2 types --- charcater device file and block device file type field in the file's inode structure Answer b--- block device file c--- character device file

How to switch to a super user status to gain privileges?

Answer

Use su command. The system asks for password and when valid entry is made the user gains super user (admin) privileges.

What are shell variables?

Shell variables are system environment variables.They include Answer TERM,SHELL, MAIL

P.N.V.SUNIL KUMAR

58

the output of the shell variable we can see by typing the command $>echo $TERM ansi at the prompt.

What is redirection?

Redirection is a feature in Unix where the data from the standard out put or a file,so on.can be redirected i.e divert to a file or a program and vice versa. Answer > -- out put redirection >> -- out put redirectin(appending at the last) < -- input redirection

How to terminate a process which is running and the specialty on command kill 0?

Answer

With the help of kill command we can terminate the process. Syntax: kill pid Kill 0 - kills all processes in your system except the login shell.

How to terminate a process which is running and the specialty on command kill 0?

Answer

With the help of kill command we can terminate the process. Syntax: kill pid Kill 0 - kills all processes in your system except the login shell.

How to sfind free space in unix/linux

Answer

Df and du commands are used for checking free space on disk . df -h or df -Humanreadable gives human readable format of free space.

What is the difference between soft link and hard link in unix

P.N.V.SUNIL KUMAR

59

operating system ?

Hard Links : 1. All Links have same inode number. 2.ls -l command shows all the links with the link column(Second) shows No. of links. 3. Links have actual file contents 4.Removing any link ,just reduces the link count , but doesn't affect other links. Answer Soft Links(Symbolic Links) : 1.Links have different inode numbers. 2. ls -l command shows all links with second column value 1 and the link points to original file. 3. Link has the path for original file and not the contents. 4.Removing soft link doesn't affect anything but removing original file ,the link becomes "dangling" link which points to nonexistant file.

to concatenate (attach) two strings?

For concatenating two string we use cat command. Answer Ex:- cat str1 str2

Explain the UNIX Kernel.

Answer

UNIX Kernel is heart of the operating system. UNIX kernal is loaded first when UNIX system is booted. It handles allocation of devices, cpu, memory from that ponint on.

How many prompts are available in a UNIX system?

Unix/ Linux Supports four Prompts PS1, PS2, PS3, PS4 Answer #,@,$,% are 4 prompts

P.N.V.SUNIL KUMAR

60

REFERENCES :

1. Unix and shell Programming Behrouz A. Forouzan, Richard F. Gilberg.Thomson 2. Your Unix the ultimate guide, Sumitabha Das, TMH. 2nd Edition. 3. Unix for programmers and users, 3rd edition, Graham Glass, King Ables, Pearson Education. 4. Unix programming environment, Kernighan and Pike, PHI. / Pearson Education 5. The Complete Reference Unix, Rosen, Host, Klee, Farber, Rosinski, Second Edition, TMH.

P.N.V.SUNIL KUMAR

61

You might also like