Академический Документы
Профессиональный Документы
Культура Документы
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING GITAM INSTITUTE OF TECHNOLOGY GITAM UNIVERSITY
UNIX
LAB MANUAL
Prepared by Under the guidance of
UTTAM MANDE DR G.APPARAO Assistant Professor Head Of The Department APPARAO GODI Department of CSE Assistant Professor GITAM Institute of Technology VENKATESWARLU K GITAM UNIVERSITY Assistant Professor DIVAKAR A Assistant Professor ****************************************************************************************** 1
Index
S.No 1 2 3 4 5
6
Contents Lab Objective Introduction About Lab Guidelines to Students List of Syllabus Programs Week wise exercises
Page No 3 4 5 8 9 28
About shell
10
11
LAB OBJECTIVE
Upon successful completion of this Lab the student will be able to:
1. a. Execute common commands. b. Execute Mail communication commands. 2. Use Vi Editor for creating, updating, viewing and saving the file efficiently 3. Creating directories and files efficiently 4. Grant / revoke the permissions for the user, groups, others efficiently 5. Use piping, redirection, TCC, TTY commands .efficiently 6. Search a pattern using Grep. 7. Implement Sed efficiently 8. Write shell scripts
There are 67 systems (Compaq Presario) installed in this Lab. Their configurations are as follows: Processor RAM Hard Disk Mouse : : Intel Core2 duo CPU
Software All systems are loaded with Windows XP and they contain putty using which they can connect with
Systems are assigned numbers and same system is allotted for students when they do the lab.
4
Guidelines to Students How to login to the system Connecting with server The student has to run putty.exe then putty will be opened ,there he has to enter host name or ip address of Server then click on open
Login in as a user
5
UNIX Lab Manual Then a login form will be displayed and student need to enter login id and password Then a session will be opened with $ prompt where student can work on server
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
6
UNIX Lab Manual 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 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 show.c contains the following lines : main() { printf( welcome to GNEC ); } 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 GNEC
6 . Grep extractions .
7 . Sed implementations.
8 . Shell programming
8
Synopsis: date [-options] [+format] Diplays the time and date cal Synopsis: cal [[month] year] Displays the calendar for a month or a year. who Synopsis: who [options][am i] Displays all users currently logged into the system passwd Synopsis: passwd Changes the user password Synopsis :man commandname man Display manual of any command name tty Synopsis: tty Displays name of a terminal. script Synopsis: sript [filename] Records interactive session. clear Synopsis: clear Clears monitor screen. whoami Synopsis: whoami displays user information bc Synopsis: bc Calculator.
H, u
a, g a,n, r,s,
Week1 exercises: 1. Change the password. 2. Load your work into some file.
9
10
UNIX Lab Manual 3. Check any leap years feb month. 4. Check the users who are not working since 5min. 5. Check man man and write your observations. 6. Print date in the Tuesday July 06/07/2010 format. 7. Display result of 33/5 in floating value.
Week2 Practice Session 1. Log in to the system 2. Practice the following file/directory handling utilities with options
10
11
COMMAND Synopsis and discription UNIX Lab Manual NAME Synopsis: file To view the characteristics of a file. cat Synopsis: cat [options][file-list] Concatenates files.it may also used to display files or create new files. touch Synopsis: touch [options][file list] To view file vi Synopsis: vi[-options][file-name] Used to create a new file or edit an existing file. Synopsis : cp[-options] source destination Copies files or directories from source to the cp destination. mv Synopsis: mv[-options] source destination Moves a files or directory from source to destination ls Synopsis: ls[-options][pathname] Lists all the contents of the directory. find Synopsis: find pathname criteria Finds a file or directory based on criteria. head Synopsis: head[-options][file-list] Displays lines at the beginning of a file (default is 10 lines). tail Synopsis :tail[-options][file-list] Displays lines at the end of a file (default is 10 lines). more Synopsis: more[-options][file-list] Displays the contents of a file one screenful at a time rm Synopsis: rm[options]list Removes ( deletes) files or directories mkdir Synopsis: mkdir [-options] directory-list Creates one or more directories Synopsis: rmdir directory-list Removes ( deletes) directories rmdir Synopsis: cd[directory] Changes the current directory defined by the cd pathname. pwd Synopsis: pwd displays the absolute pathname of the current (working)directory wc Synopsis: wc[-options][file-list] Displays the number of lines, words,and characters 11 in a file.
Important option
n,s,t,u,v,e
p,i,r f,i l,d,n,r,t,u,c,p.R,1,i a,n, -N -N,+N,b,c,l,r C,d,f,l,r,s, u,w,lines,+nmbr f,i,r, P,m r,s,
a, g
12
Week2 exercises: 1. Create two files and concatenate into file using cat. 2. Remove directory without deleting files in directory 3. Check the group permissions of any file 4. Display the characteristics of any file. 5. Display number of characters in any file. 6. Display the first 5 lines and last 20 lines in any file.
Week 3 Practice Session 1.Login into system. 2.Execute the mail commands with options. Command Talk Description Synopsis:talk user-id [terminal] Used to create a chatting environment between wo users that are logged into the same or a
12
Options
13
Write Mail
mesg
UNIX Lab Manual different system. Synopsis:write user-id [terminal] Used to send a meesage to a receiver logged into the same or a different system from the sender. Synopsis: mail[receiver-list] Used to read or send email.When it is used without argument, it is in the read mode. When an argument is used,it is in the send mode. Synopsis: mesg y/n Allows and disallows messges coming from other user Synopsis: wall To send a broadcast message to all users
wall
Week3 lab Excercises : 1. Send mail to other user. 2. Read the mail you sent to yourself. 3. block the messages from others 4. reply to the message 5. Use talk command to exchange messages. 6. Write command to send message to your friend.. 7. Find the path of your mbox 8.broadcast hai to all
Week 4 Practice Session 1. Login into the system. 2. Execute Grant and Revoke commands for user group and other. Command Chmod Chown Description Synopsis:chmod[-option]mode list Sets or changes the permission of a list of files or directories. Synopsis: chown[-option] owner [:group]
13
Options R R
14
UNIX Lab Manual list Changes the owner (and the group associated to) a list of files or directories. Synopsis:chgrp[-option] group list Changes a group associated with a list of files or directories. Synopsis:umask[mask] Displays or sets the default pemission for newly created files or directories. Synopsis:groups [user-id] Displays the users group.
3.Execute Piping commands Use of Redirection mask Input 0 Output 1 Error w 2 2 2 < > file 1
Tee
Week 4 Exercises: 1. Change the permission of any file (add execute permission to group) a. Using symbolic form b. Using Octal form 2. change group of any file? 3.set the default write,read permissions to all? 4. Using piping display the 5th line to 10th line in any file 5.check the group id and users logged in
14
15
UNIX Lab Manual 6. Using redirection send the output of any command to file and monitor. 7. Change the default permissions of files using umask to rw_r_ _r_ _ Week 5 : 1. Login into the system. 2. Execute grep commands r. Command e grep
fgrep
grep
Description Synopsis: egrep[options]regexpr.[filelist] Selects lines that match the regular expression. Synopsis:fgrep[options]string[file-list] Selects lines that match the string. Synopsis:grep[options]regexpr[file-list] Selects lines match the regular expression.
Options b, c, l,n,s,v,x,f
b,c,i,l,n,s,v,x,f
b,c,i,l,n,s,v,x,f
Week 5Exercise: 1.Write a grep (or egrep) command that selects the lines from file 1 that have exactly 3 characters. 2. Write a grep (or egrep) command that counts the number of blank lines in file1. 3. Write a grep (or egrep) command that selects the lines from file1 that start with the string UNIX and end with the string UNIX. 4. Write a grep (or egrep) command that selects the lines from file 1 that start with 1 or more blank spaces and end with 1or more blank spaces. 5. Write a grep (or egrep) command that selects the lines from file1 that have atleast 2 digits without any characters in between. 6. Write a grep (or egrep) command that selects the lines from file 1 that start with A to E or M to P,inclusive.
15
16
UNIX Lab Manual 7. Write a command that selects the lines that have only one floating point (not an integer) number. The line should not have any other characters. 8. Write a command that selects the lines that have only one octal number(the octal number should start with zero ).The line should not have any other charaters. 9. Write a command that ,using an input file,creates an output file.the output file is a same as the input file,but it contains only the lines that are a five character palindrome. 10. Use grep to simulate each of the following commands(if possible) a.uniq file1 b.wc -l c.tr ABC *** file1 d.sort file1 11.Write a grep (or egrep) command that selects a line from file1 whose last non blank character is A. 12. Write a grep (or egrep) command that selects a line from file1 that start with one or more blank spaces.
Week 6
1. Log in to the system 2. Practice the following sed commands Category Line Number Command = Description Writes the line number 16
17
Files Branch
r w : b t h H g G x
Hold Space
Quit
Week 6 Exercises: 1. Show the result of the sed command Sed s/bc*./z/ On the following file :
17
18
sed s/:?.?/z/ On the following file : :a???????? eeeeeefffff?hhhh aaa::?????? :?.\? 3 . Show the result of the sed command sed s/^\$[0-9][0-9]$/z/ On the following file : $$$$$$$ $10 abc$ $ 4 . what is done by the following command ? sed 32,45s/[()]//g file1 5 . What is done by the following script ? 10h 11,15H 10,15d 20G 6 . Write sed command that deletes the character before the last line in a file . character in each
7 . Write sed command that deletes the second word in each line in a file . 8 . Write a sed command that swaps the first and last character in each line in a file .
18
19
UNIX Lab Manual 9 . Write a sed command that delets any integer in each line in a file . 10 . Write a sed script to move lines 22 to 33 after line 9 . 11 . Write a sed command that extracts the year from a date in the form mm/dd/yy . 12 . Write a sed command that , using an input file , creates an output file . Each line in the output file is the same as the corresponding line in the input file except that the first and the last words are swapped . 13 . Can we simulate the following command using only a sed command tail -40 file1 .
20
week 7 exercises
1. Write a shell script to find G.C.D. of two numbers 2. Write a shell script to solve the expression (a+b) 2 3. write shell script to display the terminal id of given user
21
22
23
24
25
Output 2: try this [cse3c23@oracle ~]$ sh -x eo.sh --------------------------------------------------------------------------------------------------------------------FIBONACCI 3.write a shell script to display Fibonacci series FIBONACCI echo enter the number of terms read n f1=0 f2=1 i=1 echo $f1 echo $f2 while [ $i -le $n ] do f3=`expr $f1 + $f2` f1=$f2 f2=$f3 i=`expr $i + 1` echo $f3 done exit 0 Output 1: [cse3c23@oracle ~]$ sh fb.sh enter the number of terms 5 0 1 1 2 3 5 8 25
26
Week 9 exercises 1. Write a shell script that computes the gross salary of a employee according To the following rules a) if basic salary is < 1500 then HRA=10% of the basic salary and DA=90% of basic b) if basic salary is >=1500 theen HRA=Rs 500 and DA=98% of basic The basic salary is entered interactively through the keyboard 2. Write an interactive shell program for copying, removing, renaming & linking 3. 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 4. Verify executable files in your directory
Week 10 exercises
26
27
27
28
UNIX Commands
Command . (dot) : (colon) Alias Description Synopsis:. Command Reads file from the current shell. Synopsis: (null command) Does nothing (a placeholder). The exit status is always true. Synopsis: alias name definition alias [name=definition] #Korn and Bash alias[name definition] #C shell Lists existing aliases or creates new alias for a command. Synopsis: awk [options] script [file-list] Selects and processes specified lines in the input file. Synopsis: basename pathname [argument] Extracts base name or extension of a path name. Synopsis: bash Creates a new bash shell. Synopsis: bc Calculator. Synopsis: bg [job_number] Moves a suspended job to the background. Synopsis: break Forces a loop to terminate. Synopsis: breaksw Terminates execution of case commands. Synopsis: cal [[month] year] Displays the calendar for a month or a year. Synopsis: case string in pat) command (s);; pat) command (s);; ... esac Creates a multiway selection. Options
-F, -f
28
29
Command Cat
Description Synopsis: cat [-options] [file_list] Concatenates files.It may also be ised to display files or create new files. Synopsis: cd [directory] Changes the current directory to the directory defined by the pathname.If the pathname is missing,the home directory becomes the working directory. Synopsis: chgrp [-option] group list Changes a group associated with a list of files or directories. Synopsis: chmod [-option] mode list Sets or changes the permission of a list of files or directories Synopsis: chown [-option] owner [:group]list Changes the owner (and the group associated to) a list of files or directories Synopsis: clear Clears monitor screen Synopsis: cmp [-options] file1 file2 Determines if files are identical Synopsis: comm file1 file2 Displays common lines in two files Synopsis: continue Continues with the next iteration of the loop Synopsis: cp [-options] source destination Copies files or directories from source to destination Synopsis: csh Creates a new C shell Terminates (aborts) a foreground job
Cd
Chgrp
Chmod Chown
R R
l ,s
29
30
Ctrl+z
Description Synopsis: cut [-options] [file-list] Splits files into columns Synopsis: date [-options] [+format] Diplays the time and date Synopsis: diff [-options] file1 file2 diff [-options] file dir diff [-options] dir file2 diff [-options] dir1 dir2 Identifies differences between two files Synopsis: dirname pathname Extracts the directory name of a pathname Synopsis: grep [-options] regexpr [file-list] Selects lines that makes the regular expression Synopsis: groups [user id] Displays the users group Synopsis: head [-options] [file-list] Displays lines at the beginning of a file (default is at 10 lines) Synopsis: history n l-rl command_name Displays contents of the command history file Synopsis: if command Then ......... Else ......... Fi Create a two way selection Synopsis: jobs Displays the list of active objects Synopsis: kill [job_number] Kills a job Synopsis: ksh Creates a new Korn shell Synopsis: let variable=mathematical expression
30
Options
b ,c, i , l, n,s,v,x,f -N
31
Ln Lpr Command Ls
UNIX Lab Manual Evaluates a mathematical expression Synopsis: ln [-options] source link Links the source to destination Synopsis: lpr [-options] [file-list] Description Synopsis: ls [-options] [pathname] Lists the contents of a directory Synopsis: mail [receiver-list] Used to read or send mail. When it is used without Argument ,it is in the read mode. When an argument is used ,it is in the send mode Synopsis: man command-name Displays online documentation for the command Synopsis: mkdir [-options] directory-list Creates one or more directories
Man Mkdir
P,m
31
32
UNIX Lab Manual More Synopsis: more [- options] [file-list] Displays the content of a file one screenful at a time. c, d, f, l, r, s, u, w, lines, +nmbr, +/ptrn f, i
Synopsis: mv [-options] source destination Moves a file or directory from source to destination or Renames a file or directory. Synopsis: onintr [label] Runs a command when a signal received. Synopsis: passwd Changes the user password. Synopsis: paste [-options] [file-list] Combines lines of files into one single line. Synopsis: print argument list Displays contents of a variable or a string Synopsis: ps Displays information about the active processes. Synopsis: pwd Displays the absolute pathname of the current (working) directory. Synopsis: r line [ -line] command_name Reexecutes (redo) specified command in history file . Synopsis: read [options] variable-list Reads values and stores them in variables. Description Synopsis: readonly variable list Makes the variables read only. Synopsis: return [expression] Returns from function. Synopsis: rm [-options] list Removes (deletes) files or directories. Synopsis: rmdir directory-list Removes (deletes) directories. Synopsis: script [filename] Records interactive session. Synopsis: sed [-options] script [file-list] Edits specified lines in the input files and processes Them.
32
Options
f, i, r
A n, e, f
33
Select
Set
Setenv
Synopsis: select variable in list do ..... done Creates a menu environment. Synopsis: set expression set var=value #C shell set o option #Korn and Bash set +o option #Korn and Bash Sets a value for a variable or sets an option.Also unsets an option in the Korn shell when used with plus option. Sets the positional parameters. Synopsis: setenv var = value Setenv variable value Defines an exportable variable. In C shell,sets a value for an environmental variable. Synopsis: shift expression Shifts the parameters to the left. Synopsis: sleep seconds Sleeps for a number of seconds Synopsis: sort [-options] [field-specifiers] [file-list] Sorts or merges files. Synopsis: source command Executes command in current shell. Synopsis: stop [job_number] Stops (suspends) a background job. Synopsis: stty Sets or unsets selected terminal input/output options. Synopsis: tail user-id [terminal] Used to create a chatting environment between two users that are logged into the same or a different system. Synopsis: tail [-options] [file] Displays lines at the end of a file(default is 10 lines). Synopsis: talk user-id [terminal] Used to create a chatting environment between two users that are logged into the same or a different system. Synopsis: tee [-option] file-list 33 Copies standard input to standard output and at the same time copies to one or more files.
b, c, d, f, m, n, r, t, u
a, g
-N, +N, b, c, l, r
34
UNIX Lab Manual Synopsis: telnet Connects the user to the remote computer defined by the argument(domain_name). Synopsis: test arguments Evaluates a relational,logical,or file expression. Synopsis: tr [-options] [string1] [string2] Translates (replaces) a set of characters (string1) with another set (string2). Synopsis: trap action signals Runs a command when a signal is received. Synopsis: tty Displays name of a terminal. Synopsis: typeset attribute variable typeset +attribute variable Associates (-) and unassociates (+) data attributes,such as numeric and justification,to a variable. Synopsis: umask [mask] Displays or sets the default permission for newly created files or directories. Synopsis: unalias alias-list Removes some or all aliases. Synopsis: uname Displays system data. Synopsis: unique [-options] [input_file] Displays the unique lines in a file. Synopsis: unset variable unset option #Cshell Unsets the value of a variable or unsets an option. Synopsis: unsetenv variable In C shell,unsets the value of an environmental variable. Synopsis: until command do body done Repeats the body until the command is successful(exit status 0). Synopsis: vi [-options] [file name] Used to create a new file or edit an existing file.
34
c,d,s
umask unalias
vi
35
Wc while
Synopsis: wc[options] [file-list] Displays the number of lines,words,and characters in a file Synopsis: while(expression) body end Repeats the body while the expression is successful (exit status 0). Synopsis: who [options][am i] Displays all users currently logged into the system. Synopsis: whoami Displays the id of the user. Synopsis: write user-id [terminal] Used to send a message to a receiver logged into the same or a different system from the sender.
c, l, w
H, u
35
36
Vi editor
What are Different Editors
Sometimes called text editor, a program that enables you to create and edit text files. There are many different types of editors, but they all fall into two general categories:
Line editors: A primitive form of editor that requires you to specify a specific line of text before you can make changes to it. Most edits are a line-at-a-time. Typing, editing, and document display do not occur simultaneously.Two common line editors in unix are sed and ex Screen editors: Also called full-screen editors, these editors enable you to modify any text that appears on the display screen by moving the cursor to the desired location.
Nowadays, the term editor usually refers to source code editors that include many special features for writing and editing source code.
What is vi?
The default editor that comes with the UNIX operating system is called vi (visual editor). [Alternate editors for UNIX environments include pico and emacs, a product of GNU.] The UNIX vi editor is a full screen editor and has two modes of operation:
Modes of Vi Editor
There are two modes of Vi works 1. Input Mode: In this mode where any key depressed is entered as text. 36
37
To Start vi
To use vi on a file, type in vi filename. If the file named filename exists, then the first page (or screen) of the file will be displayed; if the file does not exist, then an empty file and screen are created into which you may enter text.
* vi filename vi -r filename
edit filename starting at line 1 recover filename that was being edited when system crashed
To Exit vi
Usually the new or modified file is saved when you leave vi. However, it is also possible to quit vi without saving the file. Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of command is completed by hitting the <Return> (or <Enter>) key. * :x<Return> :wq<Return> :q<Return> * :q!<Return> quit vi, writing out modified file to file named in original invocation quit vi, writing out modified file to file named in original invocation quit (or exit) vi quit vi even though latest changes have not been saved for this vi call
37
38
Screen Manipulation
The following commands allow the vi editor screen (or window) to move up or down several lines and to be refreshed. ^f ^b ^d ^u ^l ^r move forward one screen move backward one screen move down (forward) one half screen move up (back) one half screen redraws the screen redraws the screen, removing deleted lines
39
Changing Text
The following commands allow you to modify text. * r R replace single character under cursor (no <Esc> needed) replace characters, starting with current cursor position, until <Esc> hit cw change the current word with new text, starting with the character under cursor, until <Esc> hit cNw change N words beginning with character under cursor, until <Esc> hit; e.g., c5w changes 5 words C change (replace) the characters in the current line, until <Esc> hit cc change (replace) the entire current line, stopping when <Esc> is hit Ncc or cNc change (replace) the next N lines, starting with the current line, stopping when <Esc> is hit
Deleting Text
The following commands allow you to delete text. 39
40
Other Commands
Searching Text
A common occurrence in text editing is to replace one word or phase by another. To locate instances of particular sets of characters (or strings), use the following commands. /string ?string n N search forward for occurrence of string in text search backward for occurrence of string in text move to next occurrence of search string move to next occurrence of search string in opposite direction
41
41
42
The Shell
Whenever you login to a Unix system you are placed in a program called the shell. You can see its prompt at the bottom left of your screen. To get your work done, you enter commands at this prompt. The shell acts as a command interpreter; it takes each command and passes it to the operating system kernel to be acted upon. It then displays the results of this operation on your screen.
1 . Features provided by the shell The shell provides you with one or more of the following features. You can:
create an environment that meets your needs write shell scripts define command aliases manipulate the command history automatically complete the command line edit the command line
42
43
UNIX Lab Manual Some shells provide more of these facilites than others. 2 . Description of different types of shell There are several different shells available for Unix; the most popular are described here. You can use any one of these shells if they are available on your system. And you can switch between the different shells once you have found out if they are available.
Bourne shell (sh) C shell (csh) TC shell (tcsh) Korn shell (ksh) Bourne Again SHell (bash)
43
44
45
No No Yes No
This switches you from your current shell to the Korn shell.
45
46
Shell Programming
Introduction to Shell Programming Shell program is series of Linux commands. Shell script is just like batch file is MS-DOS but have more power than the MS-DOS batch file. Shell script can take input from user, file and output them on screen. Useful to create our own commands that can save our lots of time and to automate some task of day today life. Variables in Linux Sometimes to process our data/information, it must be kept in computers RAM memory. RAM memory is divided into small locations, and each location had unique number called memory location/address, which is used to hold our data. Programmer can give a unique name to this memory location/address called memory variable or variable (Its a named storage location that may 46
47
System Variable BASH_VERSION=1.14.7(1) COLUMNS=80 HOME=/home/vivek LINES=25 LOGNAME=students OSTYPE=Linux PATH=/usr/bin:/sbin:/bin:/usr/sbin PS1=[\u@\h \W]\$ PWD=/home/students/Common SHELL=/bin/bash USERNAME=vivek
Meaning Our shell version name No. of columns for our screen Our home directory No. of columns for our screen Our logging name Our o/s type : -) Our path settings Our prompt settings Our current working directory Our shell name User name who is currently login to this PC
NOTE that Some of the above settings can be different in your PC. You can print any of the above variables contain as follows $ echo $USERNAME $ echo $HOME Caution: Do not modify System variable this can some time create problems.
47
48
$ vech=Bus To define variable called n having value 10 $ n=10 Rules for Naming variable name (Both UDV and System Variable) (1) Variable name must begin with Alphanumeric character or underscore character (_), followed by one or more Alphanumeric character. For e.g. Valid shell variable are as follows HOME SYSTEM_VERSION vech no (2) Don't put spaces on either side of the equal sign when assigning value to variable. For e.g.. In
48
49
(3) Variables are case-sensitive, just like filename in Linux. For e.g. $ no=10 $ No=11 $ NO=20 $ nO=2 Above all are different variable name, so to print value 20 we have to use $ echo $NO and Not any of the following $ echo $no $ echo $No $ echo $nO # will print 10 but not 20 # will print 11 but not 20 # will print 2 but not 20
(4) You can define NULL variable as follows (NULL variable is variable which has no value at the time of definition) For e.g. $ vech= $ vech="" Try to print it's value $ echo $vech , Here nothing will be shown because variable has no value i.e.
49
50
Q.2.How to Define variable xn with value Rani and print it on screen $ xn=Rani $ echo $xn Q.3.How to print sum of two numbers, let's say 6 and 3
50
51
51
52
53
How to Run Shell Scripts Because of security of files, in Linux, the creator of Shell Script does not get execution permission by default. So if we wish to run shell script we have to do two things as follows (1) Use chmod command as follows to give execution permission to our script Syntax: chmod +x shell-script-name OR Syntax: chmod 777 shell-script-name (2) Run our script as Syntax: ./your-shell-program-name For e.g. $ ./first 53
54
54
55
this purpose create bin directory in your home directory and then copy your tested version of shell script to this bin directory. After this you can run you script as executable file without using $ ./shell script-name syntax, Following are steps $ cd $ mkdir bin $ cp first ~/bin $ first Each of above command Explanation ach of above command $ cd Explanation Go to your home directory
55
56
In shell script comment is given with # character. This comments are ignored by your shell. Comments are used to indicate use of script or person who creates/maintained script, or for some programming explanation etc. Remember always set Execute permission for you script. Commands Related with Shell Programming (1)echo [options] [string, variables...] Displays text or variables value on screen. Options -n Do not output the trailing new line. -e Enable interpretation of the following backslash escaped characters in the strings: \a alert (bell) \b backspace \c suppress trailing new line \n new line \r carriage return \t horizontal tab
56
57
58
58
59
NOTE: $# holds number of arguments specified on command line. and $* or $@ refer to all
59
60
Let's take rm command, which is used to remove file, But which file you want to remove and how you will you tail this to rm command (Even rm command does not ask you name of file that would like to remove). So what we do is we write as command as follows $ rm {file-name} Here rm is command and file-name is file which you would like to remove. This way you tail to rm command which file you would like to remove. So we are doing one way communication with our command by specifying file-name. Also you can pass command line arguments to your script to make it more users friendly. But how we address or access command line argument in our script. Lets take ls command $ ls -a /* This command has 2 command line argument -a and /* is another. For shell script, $ myshell foo bar Shell Script name i.e. myshell First command line argument passed to myshell i.e. foo Second command line argument passed to myshell i.e. bar In shell if we wish to refer this command line argument we refer above as follows myshell it is $0 60
61
bp ls cal 0
3 1
-5 myf +20 *
61
62
For e.g. now will write script to print command ling argument and we will see how to access them $ cat > demo #!/bin/sh # # Script that demos, command line args # echo "Total number of command line argument are $#" echo "$0 is script name" echo "$1 is first argument" echo $2 is second argument" echo "All of them are :- $*" Save the above script by pressing ctrl+d, now make it executable $ chmod +x demo $ ./demo Hello World $ cp demo ~/bin $ demo Note: After this, For any script you have to used above command, in sequence, I am not going to show you all of the above. (5)Exit Status By default in Linux if particular command is executed, it return two type of values, (Values are used to see whether command is successful or not) if return value is zero (0), command is successful, if 62
63
63
64
65
Now will see, if condition which is used for decision making in shell script, If given condition is true then command1 is executed. Syntax: if condition then command1 if condition is true or if exit status 65
66
fi Here condition is nothing but comparison between two values, for compression we can use test or [ expr ] statements or even exist status can be also used. An expression is nothing but combination of values, relational operator (such as >,<, <> etc) and mathematical operators (such as +, -, / etc ). Following are all examples of expression: 5>2 3+6 3 * 65 a<b c>5 c > 5 + 30 -1 Type following command (assumes you have file called foo) $ cat foo $ echo $? The cat command return zero(0) on successful, this can be used in if condition as follows, Write shell script as $ cat > showfile #!/bin/sh # 66
67
68
B) If bar file not present on your disk and you give command, $ ./trmfi output. C) And if you type $ ./trmfi, What will be output. (7)test command or [ expr ]
test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0), otherwise returns nonzero(>0) for false. Syntax: test expression OR [ expression ] Now will write script that determine whether given argument number is positive. Write script as follows $ cat > ispostive #!/bin/sh # # Script to see whether argument is positive # if test $1 -gt 0
68
69
69
70
if expr [ 5 -lt 6 ]
NOTE: == is equal, != is not equal. For string Comparisons use Operator Meaning
70
71
Shell also test for file and directory types Test -s file -f file -d dir -w file -r file -x file Meaning Non empty file Is File exist or normal file and not a directory Is Directory exist and not a file Is writeable file Is read-only file Is file is executable
Logical Operators Logical operators are used to combine two or more condition at a time Operator ! expression expression1 -a expression2 expression1 -o expression2 (8)if...else...fi If given condition is true then command1 is executed otherwise command2 is executed. Syntax: if condition then Meaning Logical NOT Logical AND Logical OR
71
72
# Script to see whether argument is positive or negative # if [ $# -eq 0 ] then echo "$0 : You must give/supply one integers" exit 1 fi if test $1 -gt 0
72
73
73
74
else None of the above condtion,condtion1,condtion2 are true (i.e. all of the above nonzero or false) execute all commands up to fi fi
74
75
script with $ chmod +x elf $ ./elf 1 $ ./elf -2 $ ./elf 0 $ ./elf a Here o/p for last sample run: ./elf: [: -gt: unary operator expected ./elf: [: -lt: unary operator expected ./elf: [: -eq: unary operator expected Opps! a is not number, give number Above program gives error for last run, here integer comparison is expected therefore error like "./elf: [: -gt: unary operator expected" occurs, but still our program notify this thing to user by providing message "Opps! a is not number, give number". (10)Loops in Shell Scripts Computer can repeat particular instruction again and again, until particular condition satisfies. A group of instruction that is executed repeatedly is called a loop. (a) for loop Syntax: for { variable name } in { list } do execute one for each item in the list until the list is not finished (And repeat all statement between do and done) done Suppose, $ cat > testfor for i in 1 2 3 4 5 do echo "Welcome $i times" done Run it as,
75
76
do
76
77
77
78
78
79
do echo "$n * $i = `expr $i \* $n`" i=`expr $i + 1` done Save it and try as $ chmod +x nt1 $./nt1 7 Above loop can be explained as follows Set the value of command line argument to n=$1 variable n. (Here it's set to 7 ) i=1 Set variable i to 1 This is our loop condition, here if value of i is less while [ $i -le 10 ] than 10 then, shell execute all statements between do and done do Start loop Print multiplication table as 7*1=7 7 * 2 = 14 echo "$n * $i = `expr $i \* $n`" ....
79
80
80
81
... .. command;; patternN) command ... .. command;; *) command ... .. command;; esac The $variable-name is compared against the patterns until a match is found. The shell then executes all the statements up to the two semicolons that are next to each other. The default is *) and its executed if no match is found. For eg. Create script as follows $ cat > car # # if no vehicle name is given
81
82
82
83
Syntax: read varible1, varible2,...varibleN Create script as $ cat > sayH # #Script to read your name from key-board # echo "Your first name please:" read fname echo "Hello $fname, Lets be friend!" Run it as follows $ chmod +x sayH $ ./sayH This script first ask you your name and then waits to enter name from the user, Then user enters name from keyboard (After giving name you have to press ENTER key) and this entered name through keyboard is stored (assigned) to variable fname.
83
84
/bin/umount
84
85
by users who are currently login. Note that You can't use $ date who for same purpose, you must put semicolon in between date and who command.
85
86
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 [] 4. What do you mean by u-area (user area) or u-block? Ans : 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. 5 . What scheme does the Kernel in Unix System V follow while choosing a swap device among the multiple swap devices?
86
87
UNIX Lab Manual Ans : Kernel follows Round Robin scheme choosing a swap device among the multiple swap devices in Unix System V .
7 . How do you change File Access Permissions? Ans : Every 1. 2. 3. 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) 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 8 . Explain the layered aspect of a UNIX ystem . What are the layers? What does it mean to say they are layers? Ans : A UNIX system has essentially three main layers : 1 . The hardware 2 . The operating system kernel 3 . The user - level programs The kernel hides the systems hrdware underneath an abstract , high - level programming interface . It is responsible for implementing many of the facilities
87
88
UNIX Lab Manual that users and user - level programs take for granted . The kerne l assembles all of the following UNIX concepts from lowe r - level
9 . What is the use of grep command? Ans : 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 10 . What difference between cmp and diff commands? Ans : cmp - Compares two files byte by byte and displays the first mismatch. diff - tells the changes to be made to make the files identical
11 . What is the significance of the tee command ? Ans : 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.
88
89
UNIX Lab Manual 13 . How to terminate a process which is running and the specialty on command kill 0? Ans: 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. 14. Explain kill() and its possible return values. Ans : There are four possible results from this call : 1 . kill() returns 0. This implies tha t 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. 2 . kill() returns -1 , errno == ESRCH either no process exists with the given PID , or []
15 . What does the command $who | sort logfile > newfile do?
Ans : 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 16 . What are shell variables ? Ans : Shell variables are special variables , a name-value pair created and maintained by the shell . Example : PATH , HOME , MAIL and TERM 17 . How many prompts are available in a UNIX system? Ans : Two prompts :
89
90
UNIX Lab Manual PS1 (Primary Prompt) , PS2 (Secondary Prompt). 18 . Is it possible to create new a file system in UNIX ? Ans : Use su command . The system asks for password and when valid entry is made the user gains super user (admin) privileges. 19 . How the Kernel handles the copy on write bit of a page , when the bit i s set? Ans :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 [] 20 . Difference between the fork() and vfork() system call? Ans : 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() [] 21 . How the Kernel handles the fork() system call in traditional Unix and in the System V Unix, while swapping? Ans : 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 . 22 . What are the requirements for a swapper to work ?
90
91
UNIX Lab Manual Ans : 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 atleast 2 seconds before swapping out. 23 . What is Expansion swap ? Ans : 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 []
24 . What is Fork swap? Ans : 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. [] 25 . What are the entities that are swapped out of the main memory while swapping the process out of the main memory? Ans : 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 . 26 . Is the Process before and after the swap are the same? Give reason.
91
92
UNIX Lab Manual Ans : 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 out .
27 . What are the events done by the Kernel after a process is being
swapped out from the main memory? Ans : When Kernel swaps the process out of the primary memory , it performs the following: 1 . Kernel decrements the Reference Count of each region of the process . 2 . If the reference count becomes zero , swaps the region out of the main memory . 3 . Kernel allocates the space for the swapping process in the swap device . Kernel locks the other swapping process while
28 . What is major difference between the Historic Unix and the new BSD release of Unix System V in terms of Memory Management? Ans : 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. 29 . What is an advantage of executing a process in background? Ans : 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
92
93
UNIX Lab Manual the background. Example: cp *.* / & 30 . What Happens when you execute a program ? Ans : 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 []
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.
32 . What is a zombie?
Ans : 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(); 33 . How can a parent and child process communicate ? Ans : 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 tha t the parent can get the exit status of the []
93
94
UNIX Lab Manual 34 . How can you get/set an environment variable from a program? Ans : Getting the value of an environment variable is done by using `getenv(). Setting the value of an environment variable is done by using ` putenv().
35 . Explain fork() system call. Ans : 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, 36 . What are various IDs associated with a process? Ans : 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. 37 . Brief about the initial process sequence while the system boots up. Ans : 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:
38 . What is a shell?
94
95
UNIX Lab Manual Ans : 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. 39 .How does the inode map to data block of a file? Ans : Inode has 13 block addresses. 1 . The first 10 are direct block addresses of the first 10 data blocks in the file. 2 . The 11th address points to a one-level index block. The 12th address points to a two-level (double in-direction) index block. 3 . The 13th address points to a three-leve l(triple indirection) index block.
40 . Discuss the mount and unmount system calls Ans : 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 [] 41 . How do you create special files like named pipes and device files? Ans : 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 42 . What are links and symbolic links in UNIX file system?
95
96
UNIX Lab Manual Ans : 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 43 . What are the Unix system calls for I/O? Ans : 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
44 .What Happens when you execute a program? Ans : 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
45 . What is a FIFO ? Ans : 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 46 . What is inode?
96
97
UNIX Lab Manual Ans : 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 47 . How are devices represented in UNIX ? Ans : 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 48 . Brief about the directory representation in UNIX Ans : 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 directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries [] 49 . How is the command $cat file2 different from $cat >file2 Ans : 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. $cat >file means to create a new file $cat file means to open an existing file.
cat > file it means creating file for file cat file it means used to display the file content . 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
97
98
UNIX Lab Manual the file. Incase if the file does not exist in the directory the commond will create a newfile in file system. $cat >file means to create a new file $cat file means to open an existing file.
cat > file it means creating file for file cat file it means used to display the file content 50 . Explain the steps that a shell follows while processing a command. Ans : 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. 52. Which command is used to delete all files in the current directory and all its sub-directories Ans : #rm -fr <Directory name> # rm -rf * 53 . What is the use of the command "ls x chapter[1-5]" Ans : 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. 54 . How does the kernel differentiate device files and ordinary files? Ans : Device filles are of 2 types --- charcater device file and block device file type field in the file's inode structure b--- block device file c--- character device file
98
99
UNIX Lab Manual 55. How to switch to a supe user status to gain privileges? Ans : Use su command. The system asks for password and when valid entry is made the user gains super user (admin) privileges 56 . What are shell variables? Ans : Shell variables are system environment variables.They include TERM,SHELL, MAIL the output of the shell variable we can see by typing the command $>echo $TERM 57 . What is redirection? Ans : 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. > -- out put redirection >> -- out put redirectin(appending at the last) < -- input redirection 58 . How to terminate a process which is running and the specialty on command kill 0 ? Ans : 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.
10 0
UNIX Lab Manual Ans : Df and du commands are used for checking free space on disk . df -h or df -Humanreadable gives human readable format of free space 60 . What is the difference between soft link and hard link in unix operating system ?
Ans : 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. 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. 61. how to concatenate two FILES ? Ans : for concatenating two FILES use cat command 62 . Explain UNIX kernel . Ans : UNIX kernel is heart of the OS.UNIX kernel is loaded first when UNIX system is booted.It handles allocation of devices,CPU,memory.
100
10 1
63 . How many prompts are available in a UNIX system Ans : Unix/ Linux Supports four Prompts PS1, PS2, PS3, PS4 #,@,$,% are 4 prompts
REFERENCES: Books:
1) Unix and shell Programming A text book, B.A. Forouzan & R.F. Giberg, Thomson 2)Unix concepts and applications, Fourth Edition, Sumitabha Das, TMH. 3)Unix for programmers and users, 3rd edition, Gaham Glass & K. Ables, pearson education.. 5)Beginning shell scripting, E. Foster Johnson & other, Wile Y- India.
101