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
Index
S.No
Contents
Page No
1
Lab Objective
3
2
Introduction About Lab
4
3
Guidelines to Students
5
4
List of Syllabus Programs
8
5
Week wise exercises
9
6
Frequently used UNIX commands 28
7
Vi Editor
34
8
About shell
40
9
Introduction to shell programming 44
10
Viva Questions and Answers
83
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
INTRODUCTION ABOUT LAB
There are 67 systems (Compaq Presario) installed in this Lab. Their
configurations are as follows:
Processor
:
Intel® Core™2 duo CPU
RAM
:
3.21GB
Hard Disk
:
240GB
Mouse
:
Optical Mouse
Network Interface card :
Present
Software
All systems are
loaded with Windows XP and they contain putty using which they can connect
with
Linux 2.6.18-164.el5
Server name: oracle.gitam.edu
Systems are provided for students in the 1:1 ratio.
Systems are assigned numbers and same system is allotted for students
when they do the lab.
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
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
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
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
List of Lab Exercises as per syllabus of ¾ BTech CSE
2.
a ) Practicing common commands .
b ) Mail communication commands .
2 . Vi Editor and its text editing’s and saving this file .
3 . Creating directories and files.
4 . To grant / revoke the permissions for the user , groups , others
5 . Piping redirection ,TCC , TTY commands .
6 . Grep extractions .
7 . Sed implementations.
A ) Sample program
B ) Expressions
C ) Decision making
Week Wise Exercises
Week1 Practice Session
1.Log in to the system
2.Practice the following basic commands
Command
description
important
Name
options
date
Synopsis: date [-options] [+format]
Diplays the time and date
u
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
H, u
passwd Synopsis: passwd Changes the user password
man
Synopsis :man commandname
Display manual of any command name
tty
Synopsis: tty Displays name of a terminal.
script
Synopsis: sript [filename]
Records interactive session.
a, g
clear
Synopsis: clear
Clears monitor screen.
a,n,
r,s,
whoami Synopsis: whoami
displays user information
bc
Synopsis: bc
Calculator.
Week1 exercises:
3. Check any leap year’s 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
NAME
file
Synopsis:
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.
n,s,t,u,v,e
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.
R
cp
Synopsis : cp[-options] source destination
Copies files or directories from source to the
destination.
p,i,r
mv
Synopsis: mv[-options] source destination
Moves a files or directory from source to destination f,i
ls
Synopsis: ls[-options][pathname]
Lists all the contents of the directory.
l,d,n,r,t,u,c,p.R,1,i
find
Synopsis: find pathname criteria
Finds a file or directory based on criteria.
a,n, r,s,
head
Synopsis: head[-options][file-list]
Displays lines at the beginning of a file (default is
10 lines).
-N
tail
Synopsis :tail[-options][file-list]
Displays lines at the end of a file (default is 10
lines).
-N,+N,b,c,l,r
more
Synopsis: more[-options][file-list]
Displays the contents of a file one screenful at a
time
C,d,f,l,r,s,
u,w,lines,+nmbr
rm
Synopsis: rm[options]list
Removes ( deletes) files or directories
f,i,r,
mkdir
Synopsis: mkdir [-options] directory-list
Creates one or more directories
P,m
rmdir
Synopsis: rmdir directory-list
Removes ( deletes) directories
cd
Synopsis: cd[directory]
Changes the current directory defined by the
pathname.
a, g
pwd
Synopsis: pwd
displays the absolute pathname of the current
(working)directory
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
Description
Options
Talk
Synopsis:talk user-id [terminal]
Used to create a chatting environment between
wo users that are logged into the same or a
different system.
Write
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.
mesg
Synopsis: mesg y/n
Allows and disallows messges coming from
other user
wall
Synopsis: wall
To send a broadcast message to all users
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
Description
Options
Chmod
Synopsis:chmod[-option]mode list
Sets or changes the permission of a list of
files or directories.
list
Changes the owner (and the group
associated to) a list of files or directories.
Chgrp
Synopsis:chgrp[-option] group list
Changes a group associated with a list of
files or directories.
R
Umask
Synopsis:umask[mask]
Displays or sets the default pemission for
newly created files or directories.
Groups
Synopsis:groups [user-id]
Displays the user’s group.
3.Execute Piping commands
Use of Redirection mask
Input
0
<
file 1
Output
1
>
Error w
2
>
file2
2
>
1 file2
2
>>
file
|
Tee
who|tee whooct2
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 5
thline to 10
thline in any file
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
Description
Options
e grep
Synopsis:
egrep[options]’regexpr’.[file-list]
Selects lines that match the
regular expression.
b, c, l,n,s,v,x,f
fgrep
Synopsis:fgrep[-options]’string’[file-list]
Selects lines that match the
string.
b,c,i,l,n,s,v,x,f
grep
Synopsis:grep[-options]’regexpr’[file-list]
Selects lines match the regular
expression.
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.
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 Command Description
Modify I a c d D Inserts Text Appends Text Changes text
Deletes the pattern space
Deletes the first line of pattern space Substitute s Substitutes a pattern with a replacement string Transform y Transforms a set of characters to another set
Input/Output n
N p P l
Reads the next line into the pattern Space
Appends the next line in the file to the contents of the pattern space
Sends the content of the pattern space to the standard output
Sends only the first line of the pattern space to the standard output
List the contents of the pattern space with nonprinting characters represented by their ASCII codes
Files r
w Reads the contents of the file and appends to the pattern space Writes the contents pf the pattern space to a file
Branch :
b t
Labels a line to be used by branch(b) and test(t) commands
Branches unconditionally to the label. Branches on successful substitution
Hold Space h
H g G x
Copies the contents of the pattern space to the hold space Append the contents of the pattern space to the whole space
Copies the contents of the hold space to the pattern space Appends the contents of the hold space to the pattern space
Swaps the contents of the pattern space with the contents of the hold space
Quit q Stops processing the input file
Week 6 Exercises:
1. Show the result of the sed command
Sed “s/bc*./z/”
aaabbbcccddd
aaaabcsssss
aaaaabc
aabbss
2 .
Show the result of the sed command
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 character in each
line in a file .
7 . Write ‘sed’ command that deletes the second word in each line in a file .
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 .
Week 7
Practice session
1. Write shell script for reading two values and display them Sol:
echo "enter the values of a and b" read a b
[cse3c23@oracle ~]$ sh s.sh enter the values of a and b 345 789
the values are a=345 b=789
2. Write shell script to display number of files/directories in a directory Sol:
echo "enter the directory name" read n
ls $n |wc -w exit 0
output:
[cse3c23@oracle ~]$ sh s1.sh enter the directory name /home/cse3c23
2
[cse3c23@oracle ~]$ ls s1.sh s.sh
3. Write a shell script to read two numbers? Sol:
echo enter the values of a b and c read a b c
echo the value of a=$a echo the value of b=$b echo the value of c=$c d=`expr $a + $b + $c` echo the result is d=$d output:
[cse3c23@oracle ~]$ sh add.sh enter the values of a b and c 23 56 89
the value of a=23 the value of b=56 the value of c=89 the result is d=168
week 7 exercises
1.
Write a shell script to find G.C.D. of two numbers2.
Write a shell script to solve the expression (a+b) 23.
write shell script to display the terminal id of given userweek8
Practice session
ARMSTRONG 1.write a shell script to find an Armstrong number Armstrong Number
read n temp=$n sum=0 while [ $n - gt 0 ] do r=`expr $n % 10` sum=`expr $sum + \( $r \* $r \* $r \)` n=`expr $n / 10` done
if [ $temp -eq $sum ] then
echo $temp is armstrong else
echo $temp is not armstrong fi
exit 0 Output 1:
[cse3c23@oracle ~]$ sh a.sh enter the number
153 153 is armstrong Try this Output 2: [cse3c23@oracle ~]$ sh -x a.sh ---FACTORIAL
2.write a shell script to find factorial of a number FACTORIAL
echo enter a number read n sum=1 while [ $n -gt 1 ] do sum=`expr $sum \* $n` n=`expr $n - 1` done echo $sum exit 0 Output 1: [cse3c23@oracle ~]$ sh n.sh enter a number 6 720
[cse3c23@oracle ~]$ sh -x n.sh
---LARGEST NO
3.write a shell script to find largest number for three numbers passed with command LARGEST NUMBER if [ $1 -gt $2 && $1 –gt $3 ] then x=$1 elif [ $2 -gt $3 ] then x=$2 else x=$3 fi
echo largest number is $x exit 0 Output 1: [cse3c23@oracle ~]$ sh g.sh 12 34 45 largest number is 45 Output 2: [cse3c23@oracle ~]$ sh -x g.sh 67 23 45 + '[' 67 -gt 23 ']' + x=67
+ echo largest number is 67 largest number is 67
+ exit 0
---PERFECT NO
4.write a shell script to find a perfect number PERFECT NUMBER
echo enter a number read no
i=1 ans=0
while [ $i -le `expr $no / 2` ] do
if [ `expr $no % $i` -eq 0 ] then
ans=`expr $ans + $i` fi
i=`expr $i + 1` done
if [ $no -eq $ans ] then echo $no is perfect else
echo $no is not perfect fi Output 1: [cse3c23@oracle ~]$ sh p.sh enter a number 34 34 is not perfect Try this Output 2: [cse3c23@oracle ~]$ sh -x p.sh Week8 exercises
1. Write a program to matrix multiplication for N x N matrix.
2. Write a program to sorting of “N” numbers.
3. Write a program to sorting of “N” strings.
4. Write a program to the given element in the list or not
1.write a shell script to find reverse of a number REVERSE
echo enter a num read num rev=0 while [ $num -gt 0 ] do k=`expr $num \% 10` l=`expr $rev \* 10` rev=`expr $l + $k` num=`expr $num / 10` done
echo reverse number is $rev exit 0 Output 1: [cse3c23@oracle ~]$ sh r.sh enter a num 12345 reverse number is 54321 Output 2: try this [cse3c23@oracle ~]$ sh -x r.sh ---EVEN AND ODD
2.write a shell script to even or odd EVEN OR ODD
echo enter a number read n
i=1
while [ $i -le $n ] do
echo enter term read x if [ `expr $x \% 2` -eq 0 ] then echo $x is even else echo $x is odd fi i=`expr $i + 1` done Output 1: [cse3c23@oracle ~]$ sh eo.sh enter a number 4
enter term 3 3 is odd enter term 2 2 is even enter term 7 7 is odd enter term 8 8 is even
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
Output 2:try this
[cse3c23@oracle ~]$ sh -x fb.sh
---PALINDROME
4.write a shell script to check palindrome PALINDROME
echo enter a num read num rev=0 temp=$num while [ $num -gt 0 ] do k=`expr $num \% 10` l=`expr $rev \* 10` rev=`expr $l + $k` num=`expr $num / 10` done
if [ $rev -eq $temp ] then
echo $temp is a palindrome else
echo $temp is not a palindrome fi exit 0 Output 1: [cse3c23@oracle ~]$ sh fbb.sh enter a num 234 234 is not a palindrome Output 2: try this
[cse3c23@oracle ~]$ sh fbb.sh
Week 9 exercises
1.
Write a shell script that computes the gross salary of a employee according To the following rulesa) 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 & linking3.
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 directory4.
Verify executable files in your directory1.Write a script that will:
a. Ask the user's full name—first, last, and middle name. b. Greet the user by his or her first name.
c. Ask the user's year of birth and calculate his or her age (use e x p r).
d. Ask the user's login name and print his or her user ID ( f r o m / e t c / p a s s w d ). e. Tell the user his or her home directory.
f. Show the user the processes he or she is running.
g. Tell the user the day of the week, and the current time in nonmilitary time. The output should resemble:
"The day of the week is Tuesday and the current time is 04:07: 38 PM. "
2.Write a shell script that takes a command line argument and reports on whether it is a directory File, or a regular file, or something else.
3.write a shell script to display the ideal users at their ideal time
4.write the shell script to to take the student marks from text data and send marks to respected students throw mail
Frequently used unix commands
UNIX Commands
Command
Description
Options
. (dot)
Synopsis:. Command
Reads file from the current shell.
: (colon)
Synopsis: (null command)
Does nothing (a placeholder). The exit status is always true.
Alias
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.
Awk
Synopsis: awk [options] script [file-list]
Selects and processes specified lines in the input file.
-F, -f
Basename
Synopsis: basename pathname [argument]
Extracts base name or extension of a path name.
Bash
Synopsis: bash
Creates a new bash shell.
Bc
Synopsis: bc
Calculator.
Bg
Synopsis: bg [job_number]
Moves a suspended job to the background.
break
Synopsis: break
Forces a loop to terminate.
breaksw
Synopsis: breaksw
Terminates execution of case commands.
cal
Synopsis: cal [[month] year]
Displays the calendar for a month or a year.
case
Synopsis: case string in
pat) command (s);;
pat) command (s);;
...
esac
Command
Description
Options
Cat
Synopsis: cat [-options] [file_list]
Concatenates files.It may also be ised to display files or create
new files.
e ,n,
s ,t,
u,v
Cd
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.
Chgrp
Synopsis: chgrp [-option] group list
Changes a group associated with a list of files or directories.
R
Chmod
Synopsis: chmod [-option] mode list
Sets or changes the permission of a list of files or directories
R
Chown
Synopsis: chown [-option] owner [:group]list
Changes the owner (and the group associated to) a list of files
or directories
R
Clear
Synopsis: clear
Clears monitor screen
Cmp
Synopsis: cmp [-options] file1 file2
Determines if files are identical
l ,s
Comm
Synopsis: comm file1 file2
Displays common lines in two files
continue
Synopsis: continue
Continues with the next iteration of the loop
Cp
Synopsis: cp [-options] source destination
Copies files or directories from source to destination
Csh
Synopsis: csh
Creates a new C shell
Ctrl+z
Stops-(suspends) a foreground job
Command
Description
Options
Cut
Synopsis: cut [-options] [file-list]
Splits files into columns
Date
Synopsis: date [-options] [+format]
Diplays the time and date
Diff
Synopsis: diff [-options] file1 file2
diff [-options] file dir
diff [-options] dir file2
diff [-options] dir1 dir2
Identifies differences between two files
dirname
Synopsis: dirname pathname
Extracts the directory name of a pathname
Grep
Synopsis: grep [-options] ‘regexpr’ [file-list]
Selects lines that makes the regular expression
b ,c, i , l,
n,s,v,x,f
Groups
Synopsis: groups [user id]
Displays the user’s group
Head
Synopsis: head [-options] [file-list]
Displays lines at the beginning of a file
(default is at 10 lines)
-N
History
Synopsis: history –n l-rl command_name
Displays contents of the command history file
Else
Synopsis: if command
Then
...
Else
...
Fi
Create a two way selection
jobs
Synopsis: jobs
Displays the list of active objects
kill
Synopsis: kill [job_number]
Kills a job
ksh
Synopsis: ksh
Creates a new Korn shell
Evaluates a mathematical expression
Ln
Synopsis: ln [-options] source link
Links the source to destination
S,i,f
Lpr
Synopsis: lpr [-options] [file-list]
p
Command
Description
Options
Ls
Synopsis: ls [-options] [pathname]
Lists the contents of a directory
l , d , n ,r
t ,u , c ,r,
l ,i
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
Man
Synopsis: man command-name
Displays online documentation for the command
Mkdir
Synopsis: mkdir [-options] directory-list
Creates one or more directories
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
Mv
Synopsis: mv [-options] source destination
Moves a file or directory from source to destination or
Renames a file or directory.
f, i
onintr
Synopsis: onintr [label]
Runs a command when a signal received.
passwd
Synopsis: passwd
Changes the user password.
paste
Synopsis: paste [-options] [file-list]
Combines lines of files into one single line.
d
Synopsis: print argument list
Displays contents of a variable or a string
ps
Synopsis: ps
Displays information about the active processes.
pwd
Synopsis: pwd
Displays the absolute pathname of the current
(work-ing) directory.
r
Synopsis: r line [ -line] command_name
Reexecutes (redo) specified command in history file .
read
Synopsis: read [options] variable-list
Reads values and stores them in variables.
Command
Description
Options
readonly
Synopsis: readonly variable –list
Makes the variables read only.
return
Synopsis: return [expression]
Returns from function.
rm
Synopsis: rm [-options] list
Removes (deletes) files or directories.
f, i, r
rmdir
Synopsis: rmdir directory-list
Removes (deletes) directories.
script
Synopsis: script [filename]
Records interactive session.
A
sed
Synopsis: sed [-options] script [file-list]
Edits specified lines in the input files and processes
Select
Synopsis: select variable in list
do
...
done
Creates a menu environment.
Set
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.
Setenv
Synopsis: setenv var = value
Setenv variable value
Defines an exportable variable. In C shell,sets a value
for an environmental variable.
Shift
Synopsis: shift expression
Shifts the parameters to the left.
Sleep
Synopsis: sleep seconds
Sleeps for a number of seconds
Sort
Synopsis: sort [-options] [field-specifiers] [file-list]
Sorts or merges files.
b, c, d,
f, m, n,
r, t, u
Source
Synopsis: source command
Executes command in current shell.
Stop
Synopsis: stop [job_number]
Stops (suspends) a background job.
Sty
Synopsis: stty
Sets or unsets selected terminal input/output options.
a, g
Switch
Synopsis: tail user-id [terminal]
Used to create a chatting environment between two users that
are logged into the same or a different system.
Tall
Synopsis: tail [-options] [file]
Displays lines at the end of a file(default is 10 lines).
-N, +N,
b, c,
l, r
Talk
Synopsis: talk user-id [terminal]
telnet
Synopsis: telnet
Connects the user to the remote computer defined by the
argument(domain_name).
test
Synopsis: test arguments
Evaluates a relational,logical,or file expression.
tr
Synopsis: tr [-options] [string1] [string2]
Translates (replaces) a set of characters (string1) with another
set (string2).
c,d,s
trap
Synopsis: trap “action” signals
Runs a command when a signal is received.
tty
Synopsis: tty
Displays name of a terminal.
typeset
Synopsis: typeset –attribute variable
typeset +attribute variable
Associates (-) and unassociates (+) data attributes,such as
numeric and justification,to a variable.
umask
Synopsis: umask [mask]
Displays or sets the default permission for newly created files
or directories.
unalias
Synopsis: unalias alias-list
Removes some or all aliases.
A
(korn and
bash)
uname
Synopsis: uname
Displays system data.
a,n,
r,s,sr
uniq
Synopsis: unique [-options] [input_file]
Displays the unique lines in a file.
u,c,d
unset
Synopsis: unset variable
unset option #Cshell Unsets the value of a
variable or unsets an option.
unsetenv
Synopsis: unsetenv variable
In C shell,unsets the value of an environmental variable.
until
Synopsis: until command
do
body
done
Repeats the body until the command is successful(exit status
0).
Wc
Synopsis: wc[options] [file-list]
Displays the number of lines,words,and characters in a file
c, l, w
while
Synopsis: while(expression)
body
end
Repeats the body while the expression is successful
(exit status 0).
who
Synopsis: who [options][am i]
Displays all users currently logged into the system.
H, u
whoami
Synopsis: whoami
Displays the id of the user.
write
Synopsis: write user-id [terminal]
Used to send a message to a receiver logged into the same or a
different system from the sender.
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
2. Command Mode: Where keys are used as commands to act on text
In the command mode, every character typed is a command that does something to the text file being edited; a character typed in the command mode may even cause the vi editor to enter the insert mode. In the insert mode, every character typed is added to the text in the file; pressing the <Esc> (Escape) key turns off the Insert mode.
While there are a number of vi commands, just a handful of these is usually sufficient for beginning vi users. To assist such users, this Web page contains a sampling of basic vi commands. The most basic and useful commands are marked with an asterisk (* or star) in the tables below. With practice, these commands should become automatic.
NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place of a lowercase letter; the results will not be what you expect.
To Get Into and Out Of vi
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 edit filename starting at line 1
vi -r filename 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> quit vi, writing out modified file to file named in original invocation
:wq<Return> quit vi, writing out modified file to file named in original invocation :q<Return> quit (or exit) vi
* :q!<Return> quit vi even though latest changes have not been saved for this vi call
Unlike many of the PC and MacIntosh editors, the mouse does not move the cursor within the vi editor screen (or window). You must use the the key commands listed below. On some UNIX platforms, the arrow keys may be used as well; however, since vi was designed with the Qwerty keyboard (containing no arrow keys) in mind, the arrow keys sometimes produce strange effects in vi and should be avoided.
If you go back and forth between a PC environment and a UNIX environment, you may find that this dissimilarity in methods for cursor movement is the most frustrating difference between the two. In the table below, the symbol ^ before a letter means that the <Ctrl> key should be held down while the letter key is pressed.
* j or <Return> [or down-arrow]
move cursor down one line
* k [or up-arrow] move cursor up one line
* h or <Backspace> [or left-arrow]
move cursor left one character
* l or <Space> [or right-arrow]
move cursor right one character
* 0 (zero) move cursor to start of current line (the one with the cursor)
* $ move cursor to end of current line
w move cursor to beginning of next word
b move cursor back to beginning of preceding word
:0<Return> or 1G move cursor to first line in file
:n<Return> or nG move cursor to line n
:$<Return> or G move cursor to last line in file
Screen Manipulation
The following commands allow the vi editor screen (or window) to move up or down several lines and to be refreshed.
^f move forward one screen ^b move backward one screen
^d move down (forward) one half screen ^u move up (back) one half screen
^l redraws the screen
^r redraws the screen, removing deleted
lines
Unlike PC editors, you cannot replace or delete text by highlighting it with the mouse. Instead use the commands in the following tables.
Perhaps the most important command is the one that allows you to back up and undo your last action. Unfortunately, this command acts like a toggle, undoing and redoing your most recent action. You cannot go back more than one step.
* u UNDO WHATEVER YOU JUST DID; a simple
toggle
The main purpose of an editor is to create, add, or modify text for a file.
Inserting or Adding Text
The following commands allow you to insert and add text. Each of these commands puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of text and to put the vi editor back into command mode.
* i insert text before cursor, until <Esc> hit
I insert text at beginning of current line, until <Esc> hit * a append text after cursor, until <Esc> hit
A append text to end of current line, until <Esc> hit
* o open and put text in a new line below current line, until <Esc>
hit
* O open and put text in a new line above current line, until <Esc>
hit
Changing Text
The following commands allow you to modify text.
* r replace single character under cursor (no <Esc> needed)
R 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,
* x delete single character under cursor
Nx delete N characters, starting with character under cursor
dw delete the single word beginning with character under cursor
dNw delete N words beginning with character under cursor; e.g., d5w deletes 5 words
D delete the remainder of the line, starting with current cursor position
* dd delete entire current line
Ndd or dNd delete N lines, beginning with the current line;
e.g., 5dd deletes 5 lines
Cutting and Pasting Text
The following commands allow you to copy and paste text.
yy copy (yank, cut) the current line into the buffer
Nyy or yNy copy (yank, cut) the next N lines, including the current line, into the
buffer
p put (paste) the line(s) in the buffer into the text after the current line
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 search forward for occurrence of string in text
?string search backward for occurrence of string in text
n move to next occurrence of search string
N move to next occurrence of search string in opposite direction
Determining Line Numbers
Being able to determine the line number of the current line or the total number of lines in the file being edited is sometimes useful.
:.= returns line number of current line at bottom of screen
:= returns the total number of lines at bottom of screen
^g provides the current line number, along with the total number of lines,
in the file at the bottom of the screen
These commands permit you to input and output files other than the named file with which you are currently working.
:r filename<Return> read file named filename and insert after current line (the line with cursor)
:w<Return> write current contents to file named in original vi call
:w newfile<Return> write current contents to a new file named newfile
:12,35w smallfile<Return> write the contents of the lines numbered 12 through 35 to a new file named smallfile
:w! prevfile<Return> write current contents over a pre-existing file named prevfile
Scrolling through a file
The vi scrolling commands are useful if you just want to read text sequentially. These commands are all control characters. You will not need to hit the return or enter key after typing the command. The notation ctrl-letter means hold down the control key while pressing the letter key.
ctrl-f Scroll forward a page
ctrl-b Scroll back a page
ctrl-d Scroll forward half a page ctrl-u Scroll back half a page ctrl-e Scroll forward a line
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
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)
> Bourne shell (sh)
This is the original Unix shell written by Steve Bourne of Bell Labs. It is
available on all UNIX systems.
This shell does not have the interactive facilities provided by modern shells
such as the C shell and Korn shell. You are advised to to use another shell
which has these features.
The Bourne shell does provide an easy to use language with which you
can write shell scripts
> C shell (csh)
This shell was written at the University of California, Berkeley. It provides a
C-like language with which to write shell scripts - hence its name.
> TC shell (tcsh)
This shell is available in the public domain. It provides all the features of the
C shell together with emacs style editing of the command line.
> Korn shell (ksh)
This shell was written by David Korn of Bell labs. It is now provided as the
standard shell on Unix systems.
It provides all the features of the C and TC shells together with a shell
programming language similar to that of the original Bourne shell.
It is the most efficient shell. Consider using this as your standard interactive
shell.
> BOURNE AGAIN SHELL (bash)
This is a public domain shell written by the Free Software Foundation under
their GNU initiative. Ultimately it is intended to be a full implementation of
the IEEE Posix Shell and Tools specification. This shell is widely used
within the academic commnity.
bash provides all the interactive features of the C shell (csh) and the Korn
shell (ksh). Its programming language is compatible with the Bourne shell
(sh).
If you use the Bourne shell (sh) for shell programming consider using bash
as your complete shell environment.
Summary of shell facilities :
Bourne C TC Korn BASH
command history No Yes Yes Yes Yes
command alias No Yes Yes Yes Yes
shell scripts Yes Yes Yes Yes Yes
filename completion No Yes* Yes Yes* Yes
command line editing No No Yes Yes* Yes
job control No Yes Yes Yes Yes
________________________________________________________
* not the default setting for this shell
3 . Changing your shell
First find out which shell you are using from the shells that are available on your
system.
•
Switch to using another shell
•Changing to another login shell
> Switch to using another shell
You can switch to another shell for the remainder of your login session. To
do this enter the shell command name at the system prompt. For example:
ksh $
> Changing to another login shell
To change the shell that you enter whenever you log in to the system use
the chsh (change shell) command. Next time you login you will use the
new shell.
You must reset any shell and environment variables that you set in your
previous shell's startup file
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
take different values, but only one at a time). In Linux, there are two types of variable
1) System variables - Created and maintained by Linux itself. This type of variable defined in CAPITAL LETTERS.
2) User defined variables (UDV) - Created and maintained by user. This type of variable defined in lower LETTERS.
Some System variables
You can see system variables by giving command like $ set, Some of the important System variables are
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
System Variable Meaning
BASH_VERSION=1.14.7(1) Our shell version name No. of columns for our screen
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 COLUMNS=80
HOME=/home/vivek Our home directory
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
How to define User defined variables (UDV) To define UDV use following syntax
Syntax: variablename=value
NOTE: Here 'value' is assigned to given 'variablename' and Value must be on right side = sign For e.g.
$ no=10 # this is ok
$ 10=no # Error, NOT Ok, Value must be on right side of = sign. To define variable called 'vech' having value Bus
$ 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
following variable declaration there will be no error
$ no=10
But here there will be problem for following $ no =10
$ no= 10 $ no = 10
(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 # will print 10 but not 20 $ echo $No # will print 11 but not 20 $ echo $nO # 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=""
NULL variable.
(5) Do not use ?,* etc, to name your variable names.
How to print or access value of UDV (User defined variables)
To print or access UDV use following syntax Syntax: $variablename
For eg. To print contains of variable 'vech' $ echo $vech
It will print 'Bus' (if previously defined as vech=Bus) ,To print contains of variable 'n' $ echo $n It will print '10' (if previously defined as n=10)
Caution: Do not try $ echo vech It will print vech instead its value 'Bus' and $ echo n, It will print n instead its value '10', You must use $ followed by variable name.
Q.1.How to Define variable x with value 10 and print it on screen
$ x=10 $ echo $x
Q.2.How to Define variable xn with value Rani and print it on screen
$ xn=Rani $ echo $xn
$ echo 6 + 3
This will print 6 + 3, not the sum 9, To do sum or math operations in shell use expr, syntax is as follows Syntax: expr op1 operator op2
Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be + Addition
- Subtraction / Division
% Modular, to find remainder For e.g. 20 / 3 = 6 , to find remainder 20 % 3 = 2, (Remember its integer calculation)
\* Multiplication $ expr 6 + 3
Now It will print sum as 9 , But $ expr 6+3
will not work because space is required between number and operator (See Shell Arithmetic)
Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
$x=20 $ y=5 $ expr x / y
Q.5.Modify above and store division of x and y to variable called z
$ z=`expr x / y` $ echo $z
Note : For third statement, read Shell Arithmetic.
How to write shell script
Now we write our first script that will print "Knowledge is Power" on screen. To write shell script you can use in of the Linux's text editor such as vi or mcedit or even you can use cat command. Here we are using cat command you can use any of the above text editor. First type following cat command and rest of text as its
$ cat > first #
# My first shell script #
clear
echo "Knowledge is Power"
Press Ctrl + D to save. Now our script is ready. To execute it type command
$ ./first
This will give error since we have not set Execute permission for our script first; to do this type command
$ chmod +x first $ ./first
First screen will be clear, then Knowledge is Power is printed on screen. To print message of variables contains we user echo command, general form of echo command is as follows
echo "Message"
echo "Message variable1, variable2....variableN"
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.
Here '.'(dot) is command, and used in conjunction with shell script. The dot(.) indicates to current shell that the command following the dot(.) has to be executed in the same shell i.e. without the loading of another shell in memory. Or you can also try following syntax to run Shell Script
Syntax: bash &nbsh;&nbsh; your-shell-program-name
OR /bin/sh &nbsh;&nbsh; your-shell-program-name
For e.g. $ bash first $ /bin/sh first
Note that to run script, you need to have in same directory where you created your script, if you are in different directory your script will not run (because of path settings), For eg. Your home directory is ( use $ pwd to see current working directory) /home/vivek. Then you created one script called 'first', after creation of this script you moved to some other directory lets say
/home/vivek/Letters/Personal, Now if you try to execute your script it will not run, since script 'first' is in /home/vivek directory, to Overcome this problem there are two ways First, specify complete path of your script when ever you want to run it from other directories like giving following command
$ /bin/sh /home/vivek/first
Now every time you have to give all this detailed as you work in other directory, this take time and you have to remember complete path. There is another way, if you notice that all of our programs (in form of executable files) are marked as executable and can be directly executed from prompt
from any directory (To see executables of our normal program give command $ ls -l /bin or ls -l /usr/bin) by typing command like
$ bc
$ cc myprg.c $ cal
etc, How this happed? All our executables files are installed in directory called /bin and /bin directory is set in your PATH setting, Now when you type name of any command at $ prompt, what shell do is
it first look that command in its internal part (called as internal command, which is part of Shell itself, and always available to execute, since they do not need extra executable file), if found as
internal command shell will execute it, If not found It will look for current directory, if found shell will execute command from current directory, if not found, then Shell will Look PATH setting, and try
to find our requested commands executable file in all of the directories mentioned in PATH settings, if found it will execute it, otherwise it will give message "bash: xxxx :command not found", Still there is one question remain can I run my shell script same as these executables. Yes you can, for
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
Now created bin directory, to install your own shell
$ mkdir bin script, so that script can be run as independent program or can be accessed from any directory
$ cp first ~/bin copy your script 'first' to your bin directory
$ first Test whether script is running or not (It will run)
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
\\ backslash
For eg. $ echo -e "An apple a day keeps away \a\t\tdoctor\n"
(2)More about Quotes
There are three types of quotes " i.e. Double Quotes
' i.e. Single quotes ` i.e. Back quote
1."Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except \ and $).
2. 'Single quotes' - Enclosed in single quotes remains unchanged. 3. `Back quote` - To execute command.
For eg.
$ echo "Today is date"
Can't print message with today's date. $ echo "Today is `date`".
Now it will print today's date as, Today is Tue Jan ....,See the `date` statement uses back quote,
(3) Shell Arithmetic
Use to perform arithmetic operations For e.g.
$ expr 10 / 2
$ expr 20 % 3 # remainder read as 20 mod 3 and remainder is 2) $ expr 10 \* 3 # Multiplication use \* not * since its wild card) $ echo `expr 6 + 3`
For the last statement not the following points
1) First, before expr keyword we used ` (back quote) sign not the (single quote i.e. ') sign. Back quote is generally found on the key under tilde (~) on PC keyboards OR To the above of TAB key.
2) Second, expr is also end with ` i.e. back quote.
3) Here expr 6 + 3 is evaluated to 9, then echo command prints 9 as sum
4) Here if you use double quote or single quote, it will NOT work, For eg.
$ echo "expr 6 + 3" # It will print expr 6 + 3 $ echo 'expr 6 + 3'
Command Line Processing
Now try following command (assumes that the file "grate_stories_of" is not exist on your disk)
$ ls grate_stories_of
It will print message something like -grate_stories_of: No such file or directory
Well as it turns out ls was the name of an actual command and shell executed this command when given the command. Now it creates one question What are commands? What happened when you
type $ ls grate_stories_of? The first word on command line, ls, is name of the command to be executed. Everything else on command line is taken as arguments to this command. For eg. $ tail +10 myf
Here the name of command is tail, and the arguments are +10 and myf.
Now try to determine command and arguments from following commands: $ ls foo $ cp y y.bak $ mv y.bak y.okay $ tail -10 myf $ mail raj $ sort -r -n myf $ date $ clear
command No. of argument to this command Actual Argument ls 1 foo
cp 2 y and y.bak mv 2 y.bak and y.okay tail 2 -10 and myf mail 1 raj
sort 3 -r, -n, and myf date 0