UNIT I Notes
UNIT – I
2 – Marks
1.What is Propagation?
Radio propagation depends on the frequency of operation. In case of frequency range from 300 MHz to 30 GHz, the type of propagation is Line of Sight. The most important impairment for LOS propagation are attenuation, free space loss, noise, atmospheric absorption, multi path and refraction.
2. Define Attenuation
The strength of the signal falls off with distance over any transmission medium. In case of unguided media, the attenuation is a function of distance and the made up of atmosphere.
The transmitted signal power must be sufficiently strong to be received at the receiver. If however, the signal strength is very large, it may saturate the receiver causing distortion.. Also, higher the frequency the attenuation is also higher. It may be possible to have higher gain at higher frequencies to overcome these problem.
3. What is Free Space Loss
If the attenuation loss is assumed to be nil, still there will be free space loss which is expressed as the ratio of transmitted power to the received power. The signal strength falls inversely as square of distance. This can be overcome by designing antenna with higher gain.
4. Define Noise and how to reduce it?
Unwanted signals – referred as noise are inserted or added to the signals between transmission and reception. Various source for noise are : thermal noise, inter modulation noise, cross talk and impulse noise. Most of these noise are predictable and it is possible to reduce the impact of these noise by proper design and operation
5.What is Atmospheric absorption?
Water vapour and oxygen in the atmosphere introduces additional loss. These are frequency dependant with loss due to water vapour being maximum at 22 GHz and attenuation loss maximum at 15 GHz. Rain and fog (suspended droplets) cause scattering of radio waves that result in attenuation. Wherever, precipitation is higher the path length is to be kept shorter or lower frequency band should be used.
6. Define Multipath:
For most of the fixed communication system like satellite communication systems it is possible to locate the transmitter and receiver to have direct line of sight. However in case of mobile telephony, there can be abundant obstacles. The Signal can be reflected by such obstacles so that multiple copies of the signal with varying delays can be received. Sometimes, there maybe no direct signal. Depending on the differences in the path lengths of the direct and reflected waves, the composite signal can be either larger or smaller than the direct signal. A good reception under this condition requires positioning of the antenna at a proper site.
7. What is Refraction:
The changes in the atmospheric condition, such as density causes the radio waves to bend instead of following pure LOS propagation. If the conditions are not favorable, no signal may reach the receiver.
8. Define Multiplexing:
Multiplexing enables several user to share a medium with minimum interference or no interference. In case of wireless communication, there can be four types of multiplexing. These are Space Division Multiplexing, Frequency Division Multiplexing, Time Division Multiplexing and Code Division Multiplexing.
9. Explain Time Division Multiplexing:
|
In this the user is given the hole bandwidth for a given period of time. That is many sends can use the same frequency band , but at different point of time. Here, there must be guard time, so as to avoid co channel interference. To reduce / avoid co channel interference, precise synchronization between senders is necessary. Here, the receiver and transmitter is to synchronize precisely for proper communication.
The advantage with the TDM is that it is possible to allocate more time to a user who has heavy load. This is one of the requirement in case of internet access by the mobile user where the requested traffic is much smaller than the downloaded traffic.
10. What is Cellular Concept😕
Cellular concept is a system level idea wherein a single high power transmitter (large cell) is replaced with many low power transmitter covering a small portion of the service area. Each base station is allocated a portion of the total number of channels available to the entire system and nearby base stations are assigned different groups of channels.
16-Marks :
1.Explain Multiplexing and types of Multiplexing?
Multiplexing: Multiplexing enables several user to share a medium with minimum interference or no interference. In case of wireless communication, there can be four types of multiplexing. These are Space Division Multiplexing, Frequency Division Multiplexing, Time Division Multiplexing and Code Division Multiplexing.
Space Division Multiplexing: In this, physical space is separated for each of the user so that the interference is minimum or nil as shown below:
S1…S6 are the space segments where each pair of the user has separate space for communicationin his own channel. As the space is separated there is likely to be no interference among each pair. The transmitter power controls the radius of action. This is similar to the FM radio station thatuse the same frequency at different location without interference. However, if several frequencies (pair of user )are to be used, this may need to be modified with other multiplexing techniques
.
|
Frequency Division Multiplexing: In this the frequency is divided into several bands that are not overlapping. Each user can use the allotted band of frequency without causing interference to other user. Here also certain guard band is provided to minimize the adjacent channel interference. The
drawback of this system is that the frequency remains allocated to the user even during those times when there is no communication. It is not an efficient method as it ties up one channel to a user and also limits the number of users.
|
Time Division Multiplexing: In this the user is given the hole bandwidth for a given period of time. That is many sends can use the same frequency band , but at different point of time. Here, there must be guard time, so as to avoid co channel interference. To reduce / avoid co channel interference, precise synchronization between senders is necessary. Here, the receiver and transmitter is to synchronize precisely for proper communication.
The advantage with the TDM is that it is possible to allocate more time to a user who has heavy load. This is one of the requirement in case of internet access by the mobile user where the requested traffic is much smaller than the downloaded traffic.
TDM and FDM Combined Multiplexing:
|
It is possible to combine the FDM and TDM wherein a certain user can use a certain frequency for certain amount of time. Now there is a need for guard band as well as better synchronization to avoid both adjacent and co channel interference. One important advantage is that the system has better immunity to frequency selective interference. Also, this system provides protection against channel tapping. The disadvantage is that there needs to be proper coordination between different sends and receivers both in frequency and time domain.
|
Code Division Multiplexing: CDM was first used in military application due to its inherent security features. Currently it is extensively used in civil mobile communication applications. In this all the users trans receive the messages at the same frequency and at the same time. This is made possible when the digital transmitted codes modulates a pseudo random codes that are different for each user. Similar to FDM and TDM, to avoid interference due to codes that are closer to each other, codes are allotted to the user with a specific code space by using orthogonal code selection. This technique facilitates a large number of user to share the same frequency spectrum. Each user having a separate code when communicates adds to the background noise. As large users use the system, the noise increases thereby limiting its performance. However it provides good protection against interference and tapping. The main disadvantage of the system, is it is relatively quite complex.
2. Explain Mobile and Wireless Devices and also explain the reference model
There are a number of mobile and wireless configurations.. Mobile or mobility means the user has the access to similar telecommunication services when he is on the move. Eg: ‘Call Forwarding’ solutions etc. Wireless means that the device is able to communicate in the absence of wired connection. This facility clubbed with mobility enhances the performance of the device to get connected at different location. A number of configurations that are possible are Fixed and Wired, Mobile and wired, Fixed and Wireless, Mobile and Wireless. Out of these, the last one is the most challenging one.
Mobile and wireless devices are listed starting from simple one to more complex ones:
- Pager: A simple receiver to receiver short text messages.
- Mobile Phones: In addition to providing communication facility while on move, these devices have much advanced features.
- Personal digital assistants (PDAs) are handheld computers that were originally designed as personal organizers, but became much more versatile over the years. PDAs have many uses: calculation, use as a clock and calendar, playing computer games, accessing the Internet, sending and receiving E-mails, video recording, typewriting and word processing, use as an address book, making and writing on spreadsheets. Newer PDAs also have both color screens and audio capabilities, enabling them to be used as mobile phones (smartphones), web browsers, or portable media players. Many PDAs can access the Internet, intranets or extranets via Wi-Fi, or Wireless Wide-Area Networks (WWANs). One of the most significant PDA characteristic is the presence of a touch screen
- Palmtop/Packet computers: These are the Handheld PC that provide familiar applications from the PC in a mobile format with all the convenience and portability of a PDA. To be classed as a Handheld PC the device must be able to run Microsoft’s Windows CE (Handheld PC Platform Release), include a keyboard and few other technical hardwares.
- Notebook / Laptop: A laptop is a small mobile computer, which usually weighs 2.2-18 pounds (1-6 kilograms), depending on size, materials, and other factors. The terms laptop and notebook are often used interchangeably. As of 2007, most manufacturers use the term “notebook” (or some variant thereof) for what most end-users call a “laptop”. Laptops usually run on a single main battery or from an external AC/DC adapter which can charge the battery while also supplying power to the computer itself. Many computers also have a 3 volt cell to run the clock and other processes in the event of a power failure. As personal computers, laptops are capable of the same tasks as a desktop computer, although they are typically less powerful for the same price.
- Sensor: A sensor is wireless devices having one or more of sensors and having ability to transmit sensor information. Great deal of work is goin on these sensor that configured dynamically as network for transmission of information.
Applications: Over period of 30 years, a number of application have been developed for wireless application. Some of these are listed below:
- Mobile communication on the move to any part of the world.
- Seamless internet connectivity to the mobile device user through Wi-Fi and WiMax technologies.
- Reception of broadband multimedia applications.
- Reception of music, news, road conditions, weather reports and other broadcast information .
- Knowledge of location informtion through GPS
Referenc Model:
A generic reference model for mobile wireless communication is shown below:
Mobile Unit Base Station Switching Center
Radio link Media
The model shows the mobile unit connected to a base station through wireless media and one or more base stations may be connected to Switching center through landline or through optical fibre or through microwave link . The protocol stack consists of application layer followed by data link layer, MAC Layer and Physical Layer. Call control manages the circuit switched call, including connection setup and release. Mobility Management handles, identity, authentication, access rights procedure etc. Additional services depends on the service provider. The Data link layer provides for the reliable transmission of messages using error detection and automatic repeat request and MAC layer selects the physical channel and then establishes and releases the connection. It also multiplexes the information in TDMA format.
Mobile Unit Base Station Mobile Switching Center
|
|
|
|
|
|
|
|
|
|
|
|
Radio UG/optic/Radio
In this the mobile unit and the MSC (Mobile Switching Center) form the end systems that implement a full protocol stack as shown in the figure. The intermediate systems do not necessarily need the entire protocol stack. The functionalities of each protocol stack is described below:
- Application Layer: Various applications include service location, support for multimedia applications, GPRS, SMS, applications that can handle variations in the transmission characteristics etc.
- Transport Layer: This layer is responsible for providing end to end connection. If TCP, UDP and Internet are to used, then the quality of service, flow and congestion control etc come under this protocol stack.
- Network Layer: Network layer is responsible for routing the packets through two adjacent entities that are intermediate to the end systems. Important functions include, addressing, routing, device location and handover between different networks etc.
- Data Link Layer: Main function of this layer is to access the medium, multiplexing the different data streams, correction of transmission errors, synchronization etc. This layer is responsible for a reliable point to point connections between two devices or a point to multipoint connection.
- Physical layer: This layer is responsible for frequency selection, generation of the carrier frequency, signal detection, modulation of data on to carrier frequency and if required encryption.
3. a. Give an account Wireless Transmission: (08 marks)
300 MHz to 30GHz which is suitable frequency for mobile operation is fully occupied for various uses. These are: Television broad casts, satellite communication, Microwave devices, modern radars- defense and airfield, wireless LAN, bluetooth, GPS, etc. As the spectrum is crowded with various requirements, it is difficult to find a large spectrum for mobile communication. As the spectrum allocation is decided by the country on its own depending on its strength in related technologies, it becomes difficult to coordinates the spectrum issues for international connectivity.
Selection and allocation of a frequency band in a country depends on their own regulation. However, in order to provide transnational communications, there needs to certain standards in the usage of frequencies as well as interface standards. Towards achieving this, ITU – R(International Telecommunication Union- Radio communication – a sub organization of UN) coordinates the world wide telecommunication activities. FCC – Federal Communication Commission of America, ETSI – European Telecommunication Standard Institute of Europe, similarly TRAI – Telecommunication Regulatory Authority of India are in turn are responsible for the general planning and allocation of frequencies for mobile communication. To achieve harmonization, the ITU – R holds periodic conferences, WRC- World Radio Conference to discuss and decide frequency allocations.
Access to radio spectrum is critical requirement for all sectors using wireless technologies like media, mobile communication, defence and civil aviation. For mobile network equipment vendors, spectrum frequency harmonization has a major impact on cost at terminal and network levels. New technologies can be deployed only when the spectrum agencies and regulators give the go ahead and frequencies have been allocated.
Currently mobile operators are experiencing major increase in mobile traffic every year Addition of new services like video services, ‘always – on’ internet services have put a severe strain on the network capacity requirements.
Following table gives the frequencies that are used for analog and digital mobile communications.
1 G Systems
Systems | Base Tx | Mobile Tx | Spectrum Allocation | Number of Channels | Radio Channel Spacing |
AMPS (US) | 869-894 | 824 – 849 | 50 MHz | 832 | 30 KIHz |
NAMPS(Narrow band AMPS) (US) | 869-874 | 824 – 849 | 50 MHz | 2496 | 10KHz |
NMT 450 (Europe) | 463-468 | 453-458 | 10 MHz | 200 | 25 KHz |
NMT 900 | 461-466 | 451-456 | 50 MHz | 1999 | 12.5 KHz |
2 G Systems:
Systems | Base Tx | Mobile Tx | Spectrum Allocation | Number of Channels | Radio Channel Spacing |
IS 136 | 869-894 | 824 – 849 | 50 MHz | 832 *3= 2496 | 30 KIHz |
IS – 95 | 869-894 | 824 – 849 | 50 MHz | 64 * 9= 576 | 1.25 MHz |
GSM | 925-960 | 880-915 | 50 MHz | 124 * 8 | 200 KHz |
3.b. Define the Following terms (08 Marks)
i) Attenuation
ii) Free Space loss
iii)Noise
iv)Atmosperic absorption
Attenuation: The strength of the signal falls off with distance over any transmission medium. In case of unguided media, the attenuation is a function of distance and the made up of atmosphere.
The transmitted signal power must be sufficiently strong to be received at the receiver. If however, the signal strength is very large, it may saturate the receiver causing distortion.. Also, higher the frequency the attenuation is also higher. It may be possible to have higher gain at higher frequencies to overcome these problem.
Free Space Loss: If the attenuation loss is assumed to be nil, still there will be free space loss which is expressed as the ratio of transmitted power to the received power. The signal strength falls inversely as square of distance. This can be overcome by designing antenna with higher gain.
Noise: Unwanted signals – referred as noise are inserted or added to the signals between transmission and reception. Various source for noise are : thermal noise, inter modulation noise, cross talk and impulse noise. Most of these noise are predictable and it is possible to reduce the impact of these noise by proper design and operation
Atmospheric absorption: Water vapour and oxygen in the atmosphere introduces additional loss. These are frequency dependant with loss due to water vapour being maximum at 22 GHz and attenuation loss maximum at 15 GHz. Rain and fog (suspended droplets) cause scattering of radio waves that result in attenuation. Wherever, precipitation is higher the path length is to be kept shorter or lower frequency band should be used.
4. Explain Frequency Reuse and Channel Assignment strategies:
Each cellular base station is allocated a group of radio channels to be used within a small geographic area called a cell. The power of base station antennas are limited to cover designated cell area only to avoid interference with other cells. The design process of selecting and allocating channels groups for all of the cellular base stations within a system is called frequency reuse or frequency planning
For the ease of covering the entire region without gaps, hexagonal shape is selected. Also, the base station transmitter is normally kept either at the center or at the corner. Omni directional antennas are used in case of center location and sectored directional antennas are used in case corner location.
Consider a cellular system has a total of S duplex channels available for use. Let each cell is allocated a group of k channels and if the S channels are divided among N cells into unique and disjoint channel groups, which each have the same number of channels, the total number of available ratio channels can be expressed as S=kN. The N cells which collectively use the complete set of available frequencies is called a cluster. If a cluster is replicated M times within the system, the total number of duplex channels C can be used as a measure of capacity and is given as C = MkN = MS.
|
As can be seen, the capacity of a cellular system is directly proportional to the number of times a cluster is replicated in a fixed service area. The factor N is called cluster size and it is estimated for hexagonal shape as N=i2 + ij + j2. In this case for i= 1 and j = 1, N is 3; for i=1 and j=2, N is 7; for i=2 and j=2, N = 12 and so on. If the cell area is kept and constant and the value of N is reduced, more clusters are required to cover the entire area. This gives rise to higher capacity to the system. However, small value of N gives rise to co channels repeated at closer distance compared with that of larger clusters. The frequency re use factor of a cellular system is given by 1/N, as each cell in a cell is assigned only 1/N of available channels.
To find the nearest co channel neighbors of a particular cell one must do the following: Move i cells along any chain of hexagon and then turn 60 degrees counter clockwise and move j cells. This is illustrated in the following figure for i=3 and j=2.
|
Channel Assignment strategies:
Channel assignment strategies can be classified as Static and Dynamic. When fixed number of channels are assigned to a cell, it is called fixed channel assignment. Sometimes, this may result in traffic in some cells getting overloaded while in others under loaded. Hence, it is not a method to manage traffic efficiently. Other variation is, a cell is allowed to borrow channels from neighboring cells if its channels are filled up. The mobile switching center supervises such activity.
In case of dynamic channel assignment, voice channels are assigned by MSC based on request from the Base stations. However, before the MSC need to keep a strict account on frequency use in candidate cell, the reuse distance of the channel and other cost functions etc. Although this method likely to avoid blocking of the channels and provides efficient use, the MSC need to tack a lot of data like, channel occupancy, traffic distribution, RSSI (Radio Signal Strength Indications of all channels) on a continuous basis. This increases the storage and computational load on the system but provides the advantage of increased channel utilization.
5. How to Improve the coverage and the capacity of cellular systems:
In order to enhance the capacity of the cellular system, certain techniques are followed. These are cell splitting, sectoring and zone microcell approaches etc. Cell splitting allows the orderly growth of the cellular system. Sectoring uses directional antennas to further control the interference and frequency reuse of channel. The micro cell zone concept distributes the coverage of a cell and extends the cell boundary to hard to reach places. While cell splitting increases the number of base stations, sectoring and zone micro cells rely on base stations antenna placements to improve capacity by reducing co channel interferences.
Cell Splitting:
It is the process of subdividing a congested cell into smaller cells, each with its own base station and a corresponding reduction in antenna height and transmitter power. It increases the capacity of the system as the number of times the channels are reused. BY defining new cells which have a smaller radius and by installing these smaller cells between existing cells, capacity increases due to the additional number of channels per unit area. Cell splitting is shown below:
|
If every cell were reduced such that the
radius of every cell is reduced to half, then
it will required approximately four smaller cells to cover the same area. The increased number of cells would increase the number of clusters over the coverage region, which in turn would increase the number of channels and thus capacity in the coverage area. While allocating the channels, frequency reuse plan is preserved.
As can be seen in the figure, microcell base station labeled G was placed half way between two larger stations utilizing the same channel as G. Similar method is followed while allocating channels to other micro cells. In this case each cell is allowed to transmit only a power that is equal to 1/ 16th that of original transmitter power so as to cover the smaller area.
Essentially, cell splitting achieves capacity improvement by essentially rescaling the system. That is by decreasing the cell radius R and keeping the co channel reuse ration D / R unchanged, cell splitting increases the number of channels per unit area.
Sectoring: IN this, the cell radius is kept unchanged, but methods are used to decrease the Ratio D / R. In this , sectoring improves the SIR so that the cluster size may be reduced. It replaces the omni directional antenna at the center or directional antennas at the corner with three directional antenna at the center if the cell is divided into three sectors. Each of the directional antennas cover a sector of 120 degrees as shown in the following figure
|
|
When sectoring is employed, the channels used in particular cell are broken down into sectored groups and are used only within a particular sector. Assuming a seven cell reuse, for the case of 120 deg sectors, the number of interferers in the first tier is reduced from six to two. This is because only two of the six channels cells receive interference with a particular sectored channel group. With this, the resulting SIR is found to be 24.2 db instead of 17 db.
This enhancement in the SIR, allows one to decrease the cluster size N in order to improve the frequency reuse and thus the capacity of the system
In particular system, further improvement in SIR is achieved by down tilting the sector antennas such that the radiation pattern in the vertical plane has a notch at the nearest co channels cell distance. BY going in for 7 cell reuse pattern instead of 12 cell pattern gives raise to a increase in capacity of 12 / 7 = 1.714 times.
However, the penalty for improved S/I and the resulting capacity improvement from the shrinking cluster size is an increased number of antennas at each base station. Also as the sectoring reduces the coverage areas of a particular group of channels, the number of hand off increases. This increases the load on the switching and control link elements of the mobile system.
|
Microcell Zone : In this each of the three zone sites are connected to a single base station and share the same radio requirement. The zones are connected by coaxial cable, fibre optic cable or microwave link to the base station. As the mobile travels within the cell, it retains the same channel thus avoiding the handoff and associated complexity. The base station simply switches the channels to a different zone site. The advantage of the zone cell technique is that while the cell maintains a particular coverage radius, the co channel interference in the cellular system is reduced such a large central base station is replaced by several lower powered transmitters on the edges of the cell.
Decreased co channel interferences improves the signal quality and also leads to an increase in capacity without the degradation in trucking efficiency caused by the sectoring. For satisfactory performance, and SIR of 18 db is required. For a system with N= 7, a D/ R of 4.6 was shown to achieve this. With respect to Zone microcell, since the transmission is confined to a particular zone, this implies that the D / R ratio, can be improved as the R value is now equal to the radius of the cell and is equal to the twice the length of the hexagon radius. Thus, instead of D / R ratio of 4.6 for cluster size of 7, the D / R ratio becomes 3 with the microcell concept. This facilitates the cluster size to be reduced from 7 to 3, thereby increasing the capacity 7 / 3 = 2.33 times. Hence for the same SIR requirement of 18 db, the system provides significant increase in capacity over conventional cellular planning.
MOBILE COMMUNICATION
IT2402 MOBILE COMMUNICATION 3 0 0 3
UNIT I WIRELESS COMMUNICATION 7
Cellular systems- Frequency Management and Channel Assignment- types of handoff and their characteristics, dropped call rates & their evaluation -MAC – SDMA – FDMA – TDMA – CDMA – Cellular Wireless Networks
UNIT II WIRELESS NETWORKS 9
Wireless LAN – IEEE 802.11 Standards – Architecture – Services – Mobile Ad hoc Networks- WiFi and WiMAX – Wireless Local Loop
UNIT III MOBILE COMMUNICATION SYSTEMS 11
GSM-architecture-Location tracking and call setup- Mobility management- Handover-Security-GSM SMS –International roaming for GSM- call recording functions-subscriber and service data mgt –-Mobile Number portability -VoIP service for Mobile Networks –GPRS –Architecture-GPRS procedures-attach and detach procedures-PDP context procedure-combined RA/LA update procedures-Billing
UNIT IV MOBILE NETWORK AND TRANSPORT LAYERS 9
Mobile IP – Dynamic Host Configuration Protocol-Mobile Ad Hoc Routing Protocols– Multicast routing-TCP over Wireless Networks – Indirect TCP – Snooping TCP – Mobile TCP – Fast Retransmit / Fast Recovery – Transmission/Timeout Freezing-Selective Retransmission – Transaction Oriented TCP- TCP over 2.5 / 3G wireless Networks
UNIT V APPLICATION LAYER 9
WAP Model- Mobile Location based services -WAP Gateway –WAP protocols – WAP user agent profile- caching model-wireless bearers for WAP – WML – WMLScripts – WTA – iMode- SyncML
TOTAL = 45
TEXT BOOKS:
1. Jochen Schiller, “Mobile Communications”, Second Edition, Pearson Education, 2003.
2. William Stallings, “Wireless Communications and Networks”, Pearson Education, 2002.
REFERENCES:
1. Kaveh Pahlavan, Prasanth Krishnamoorthy, “Principles of Wireless Networks”, First Edition, Pearson Education, 2003.
2. Uwe Hansmann, Lothar Merk, Martin S. Nicklons and Thomas Stober, “Principles of Mobile Computing”, Springer, 2003.
3. C.K.Toh, “AdHoc Mobile Wireless Networks”, First Edition, Pearson Education, 2002.
CP Lab II Program
Display the files starting with the alphabet
echo ” enter the alphbet”
read ch
find -name “$ch*” -print > tmp
if [ -s tmp ]
then
echo ” the files starting with $ch are”
cat tmp
else
echo ” there are no files starting with $ch”
fi
rm tmp
find xn
echo -n “enter the value of x”
read x
echo -n ” enter the power of x”
read n
sum=1
i=1
while [ $i -le $n ]
do
sum=`expr $sum \* $x`
i=`expr $i + 1`
done
echo “the value of $x power $n is $sum”
Find the Class of the Character
if test $# -ne 1
then
echo ” enter the character data”
exit 1
fi
char=$1
case “$char” in
[0-9] ) echo ” the given arg is digit :$char”;;
[a-z] ) echo ” the given arg is lowercase letter $char”;;
[A-Z] ) echo ” the given arg is uppercase letter $char”;;
? ) echo ” the given arg is special character $char”;;
* ) echo ” enter a single character”;;
esac
Copy one string to another string
echo -n “enter the stirng”
read as
l=`echo $as | wc -c`
i=1
while [ $i -le $l ]
do
es2=`echo $as | cut -c $i`
i=`expr $i + 1`
cs3=`echo $cs3$es2`
done
echo ” the actual string is $as”
echo ” the copied string is $cs3″
Count the number of digit
echo -n ” enter the number”
read n
sd=0
while [ $n -gt 0 ]
do
a=`expr $n % 10`
sd=`expr $sd + 1`
n=`expr $n / 10`
done
echo ” the total number of digits in the given number is $sd”
Calculate the HRA
echo -n ” enter employee’s basic salary”
read bsal
if [ $bsal -gt 5000 ]
then
hra=`expr $bsal / 5`
echo “HRA = $hra”
elif [ $bsal -ge 4000 -a $bsal -le 5000 ]
then
hra=`expr $bsal / 7`
echo “HRA = $hra”
else
hra=`expr $bsal / 10`
echo “HRA = $hra”
fi
Find the Length of the String
echo -n “enter the string”
read string
l=`expr $string | wc -c`
l=`expr $l – 1`
echo ” the length of the given string $string is $l”
Check the Login
echo ” enter your login name ”
read lname
if [ $LOGNAME = $lname ]
then
echo “your login name is $lname”
else
echo ” your login name is not $lname current login name is $LOGNAME”
fi
Occurrence of the Character in a String
echo -n “enter the string:”
read s1
echo -n ” enter the character to be searched”
read c1
l=`echo $s1 | wc -c`
l=`expr $l – 1`
c=0
while [ $l -gt 0 ]
do
t=`echo $s1 | cut -c $l`
if [ $t = $c1 ]
then
c=`expr $c + 1`
fi
l=`expr $l – 1`
done
echo ” the total number of occurrence of $c1 char in the given stirng $s1 is $c”
Display the Owner of the File
echo -n ” enter the file name”
read name
ls -l > tmp
if (grep $name tmp > tmp1)
then
line=`cat tmp1 | tr -s ” ” | cut -d” ” -f3`
##echo “line:$line”
fi
check=`echo $line | wc -c`
echo $check
if test $check -gt 1
then
echo ” the owner of the file $name is $line”
else
echo “the file $name doest exists”
fi
Change the file permission
echo “enter the file name”
read fname
ls -l $fname
echo “do you want to assign read,write and execute for particular file[ y/n]”
read ch
if [ $ch = y ]
then
chmod 777 $fname
echo “permissions are given”
ls -l $fname
else
echo “permission are not given”
fi
Replace the character in a string
echo -n “enter the string”
read s1
echo -n ” enter the char to be replaced”
read ocr
echo -n ” enter the new char for replacement”
read ncr
l=`echo $s1 | wc -c`
l=`expr $l – 1`
c=0
j=1
while [ $j -le $l ]
do
t=`echo $s1 | cut -c $j`
if [ $t = $ocr ]
then
ns=`echo $ns$ncr`
else
ns=`echo $ns$t`
fi
j=`expr $j + 1`
done
echo ” the old string is $s1″
echo ” the new string is $ns”
Reverse the given number
echo ” enter the number”
read n
rn=0
while [ $n -gt 0 ]
do
a=`expr $n % 10`
rn=`expr $rn ‘*’ 10 + $a`
n=`expr $n / 10`
done
echo ” the reversed given number is $rn”
Calculate the Simple interest
echo -n “enter the principal amount : Rs”
read p
echo -n “enter the number of years”
read n
echo -n “enter the rate of interest”
read r
si=`expr “scale=2; ($p * $n * $r) / 100” | bc`
echo “simple interest = Rs.$si”
Find square and cube
echo ” enter the value”
read a
sq=`expr $a \* $a`
cu=`expr $sq \* $a`
echo ” square of $a is $sq”
echo ” cube of $a is $cu”
STUDENT DETAILS
echo STUDENT DETAILS
echo enter the name
read name
echo enter the roll number
read rno
echo enter the marks of 3 subjects
read m1 m2 m3
total=`expr $m1 + $m2 + $m3`
avg=`expr $total / 3`
echo NAME $name
echo ROLL NUMBER $rno
echo MARK1 $m1
echo MARK2 $m2
echo MARK3 $m3
echo TOTAL $total
echo AVERAGE $avg
if [ $avg -ge 90 ]
then
echo GRADE A
elif [ $avg -ge 80 ]
then
echo GRADE B
elif [ $avg -ge 70 ]
then
echo GRADE C
elif [ $avg -ge 60 ]
then
echo GRADE D
else
echo GRADE E
fi
OUTPUT
enter the name
A
enter the roll number
10
enter the marks of 3 subjects
60 70 80
NAME A
ROLL NUMBER 10
MARK1 60
MARK2 70
MARK3 80
TOTAL 210
AVERAGE 70
GRADE C
TO FIND SUM OF FIRST N NATURAL NUMBER
echo enter the value for n
read n
i=1
sum=0
until [ $i -gt $n ]
do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo sum of $n natural number $sum
OUTPUT
enter the value for n
4
sum of 4 natural number 10
TO FIND NUMBER OF VOWELS IN GIVEN STRING
echo enter the string
read s1
l=`echo $s1 | wc -c`
l=`expr $l – 1`
v=0
while [ $l -gt 0 ]
do
t=`echo $s1 | cut -c $l`
if [ $t = a ]
then
v=`expr $v + 1`
elif [ $t = e ]
then
v=`expr $v + 1`
elif [ $t = i ]
then
v=`expr $v + 1`
elif [ $t = o ]
then
v=`expr $v + 1`
elif [ $t = u ]
then
v=`expr $v + 1`
fi
OUTPUT
enter the string
engineer
the total vowels 4
SUM OF DIGITS OF A NUMBER
echo ENTER THE NUMBER
read a
sum=0
i=0
while [ $a -ne 0 ]
do
i=`expr $a % 10`
a=`expr $a / 10`
sum=`expr $sum + $i`
done
echo THE SUM OF THE DIGITS IS $sum
SAMPLE OUTPUT
ENTER THE NUMBER
45
THE SUM OF THE DIGITS IS 9
SUM AND PRODUCT OF TWO NUMBERS
Echo enter the number
read a b
c = ` expr $a + $b`
d = `expr $a \* $b`
echo the sum is : $c
echo the product is: $d
OUTPUT
enter the number 2 4
the sum is : 6
the product is: 8
String operation
PROGRAM
echo ENTER THE CHOICE
echo 1.STRING LENGTH
echo 2.STRING CONCATENATION
echo 3.STRING COMPARISION
read ch
case $ch in
1)c=$1 | wc -c
c=`expr $1 -1`
echo LENGTH OF $1 IS $c;;
2)c=`expr$1$2`
echo CONCATENATED STRING IS $c;;
3)if [ $1 -eq $2 ]
then
echo STRINGS ARE EQUAL
else
echo STRINGS ARE NOT EQUAL
fi;;
*)echo WRONG CHOICE
Esac
OUTPUT
[eeepss08@eeelinum]$sh string.sh super man
ENTER THE CHOICE
1.STRING LENGTH
2.STRING CONCATENATION
3.STRING COMPARISON
2
THE CONCATENATED STRING IS SUPERMAN
STRING PALINDROME
echo Enter a string
read str
l=`expr $str | wc -c`
l=`expr $l – 1`
while [ $l -gt 0 ]
do
s=`expr $str | cut -c $l`
new=`expr $new$s`
l=`expr $l – 1`
done
if [ $new = $str ]
then
echo It is a Palindrome
else
echo It is not a Palindrome
fi
SAMPLE OUTPUT
Enter a string
refer
It is a Palindrome
FACTORIAL OF A GIVEN NUMBER
echo enter the limit
read a
f=0
s=1
t=`expr $f + $s`
echo the fibonacci series is
echo $f
echo $s
i=1
while [ $i -le $a ]
do
echo $t
f=$s
s=$t
t=`expr $f + $s`
i=`expr $i + 1`
done
OUTPUT
enter the limit
5
the fibonacci series is
0
1
1
2
3
5
8
FACTORIAL OF A GIVEN NUMBER
echo enter the number
read a
fact=1
i=1
while [ $i -le $a ]
do
fact=`expr $fact \* $i`
i=`expr $i + 1`
done
echo the factorial of $a is $fact
OUTPUT
enter the number
5
the factorial of 5 is 120
COUNTING VOWELS
echo enter the string
read str
l=`expr $str | wc -c`
l=`expr $l – 1`
while [ $l -gt 0 ]
do
s=`expr $str | cut -c$l`
if [ $s = a -o $s = A ]
then
count=`expr $count + 1`
elif [ $s = e -o $s = E ]
then
count=`expr $count + 1`
elif [ $s = i ]
then
count=`expr $count + 1`
elif [ $s = o ]
then
count=`expr $count + 1`
elif [ $s = u ]
then
count=`expr $count + 1`
fi
l=`expr $l – 1`
done
if [ $count -eq 0 ]
then
echo No Vowel
else
echo $count
fi
ARITHMETIC OPERATIONS USING SWITCH CASE
h=1
while [ $h -eq 1 ]
do
echo enter two numbers
read a b
echo enter your choice
echo 1.add 2.subtract 3.multiply 4.divide
read ch
case $ch in
1)c=`expr $a + $b`
echo the sum is $c;;
2)c=`expr $a – $b`
echo the difference is $c;;
3)c=`expr $a \* $b`
echo the product is $c;;
4)c=`expr $a / $b`
echo the quotient is $c;;
echo wrong choice entered;;
echo enter 1 to continue
read h
done
OUTPUT
enter two numbers
3 3
enter your choice
1.add 2.subtract 3.multiply 4.divide
1
the sum is 6
enter 1 to continue
1
enter two numbers
4 2
enter your choice
1.add 2.subtract 3.multiply 4.divide
3
the product is 8
enter 1 to continue
2
GE 2155 – COMPUTER PRACTICE LABORATORY
GE2155
COMPUTER PRACTICE LABORATORY – II 0 1 2 2
LIST OF EXPERIMENTS
1. UNIX COMMANDS 15
Study of UNIX OS – Basic Shell Commands – Unix Editor
2. SHELL PROGRAMMING 15
Simple Shell program – Conditional Statements – Testing and Loops
3. C PROGRAMMING ON UNIX 15
Dynamic Storage Allocation-Pointers-Functions-File Handling
TOTAL: 45 PERIODS
HARDWARE / SOFTWARE REQUIREMENTS FOR A BATCH OF 30 STUDENTS
Hardware
- 1 UNIX Clone Server
- 33 Nodes (thin client or PCs)
- Printer – 3 Nos.
Software
- OS – UNIX Clone (33 user license or License free Linux)
-
Compiler – C
MISRIMAL NAVAJEE MUNOTH JAIN ENGINEERING COLLEGE
THORAPAKKAM, CHENNAI-600 096
DEPARTMENT OF INFORMATION TECHNOLOGY
Code/Subject: GE 2155 – COMPUTER PRACTICE LABORATORY —II
List of experiments
INDEX | ||
Sl. No |
Name of the Experiments |
Page No. |
1 | Study of UNIX Operating system | |
2 | Study of Basic Shell Commands | |
3 | Study of UNIX vi editor | |
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
|
|
10 |
|
Study of UNIX OS
EX. NO. :
DATE :
AIM: To study the UNIX OS.
What is UNIX?
UNIX is an operating system which was first developed in the 1960s, and has been under constant development ever since. By operating system, we mean the suite of programs which make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops and laptops.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which provides an easy to use environment. However, knowledge of UNIX is required for operations which aren’t covered by a graphical program, or for when there is no windows interface available, for example, in a telnet session.
Types of UNIX
There are many different versions of UNIX, although they share common similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X.
The UNIX operating system
The UNIX operating system is made up of three parts; the kernel, the shell and the programs.
The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.
The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt (% on our systems).
The adept user can customise his/her own shell, and users can use different shells on the same machine. Staff and students in the school have the tcsh shell by default.
The tcsh shell has certain features to help the user inputting commands.
Filename Completion – By typing part of the name of a command, filename or directory and pressing the [Tab] key, the tcsh shell will complete the rest of the name automatically. If the shell finds more than one name beginning with those letters you have typed, it will beep, prompting you to type a few more letters before pressing the tab key again.
History – The shell keeps a list of the commands you have typed in. If you need to repeat a command, use the cursor keys to scroll up and down the list or type history for a list of previous commands.
Files and processes
Everything in UNIX is either a file or a process.
A process is an executing program identified by a unique PID (process identifier).
A file is a collection of data. They are created by users using text editors, running compilers etc.
Examples of files:
-
a document (report, essay etc.)
-
the text of a program written in some high-level programming language
-
instructions comprehensible directly to the machine and incomprehensible to a casual user, for example, a collection of binary digits (an executable or binary file);
-
a directory, containing information about its contents, which may be a mixture of other directories (subdirectories) and ordinary files.
The Directory Structure
All the files are grouped together in the directory structure. The file-system is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash / )
Most UNIX file system types have a similar general structure, although the exact details vary quite a bit. The central concepts are superblock, inode, data block, directory block, and indirection block. The superblock contains information about the file system as a whole, such as its size (the exact information here depends on the file system). An inode contains all information about a file, except its name. The name is stored in the directory, together with the number of the inode. A directory entry consists of a filename and the number of the inode which represents the file. The inode contains the numbers of several data blocks, which are used to store the data in the file. There is space only for a few data block numbers in the inode, however, and if more are needed, more space for pointers to the data blocks is allocated dynamically. These dynamically allocated blocks are indirect blocks; the name indicates that in order to find the data block, one has to find its number in the indirect block first.
Like UNIX, Linux chooses to have a single hierarchical directory structure. Everything starts from the root directory, represented by /, and then expands into sub-directories instead of having so-called ‘drives’. In the Windows environment, one may put one’s files almost anywhere: on C drive, D drive, E drive etc. Such a file system is called a hierarchical structure and is managed by the programs themselves (program directories), not by the operating system. On the other hand, Linux sorts directories descending from the root directory / according to their importance to the boot process.
Linux, like Unix also chooses to be case sensitive. What this means is that the case, whether in capitals or not, of the characters becomes very important. This feature accounts for a fairly large proportion of problems for new users especially during file transfer operations whether it may be via removable disk media such as floppy disk or over the wire by way of FTP.
The image below shows the file system of Linux
The following bin/ dev/ home/ lost+found/ proc/ sbin/ usr/ boot/ etc/ lib/ mnt/ root/ tmp/ var/ are explained in detail.
/sbin – This directory contains all the binaries that are essential to the working of the system. These include system administration as well as maintenance and hardware configuration programs.
/bin – In contrast to /sbin, the bin directory contains several useful commands that are used by both the system administrator as well as non-privileged users.
/boot – This directory contains the system.map file as well as the Linux kernel. Lilo places the boot sector backups in this directory.
/dev – This is a very interesting directory that highlights one important characteristic of the Linux filesystem – everything is a file or a directory. Look through this directory and you should see hda1, hda2 etc, which represent the various partitions on the first master drive of the system. /dev/cdrom and /dev/fd0 represent your CDROM drive and your floppy drive.
/etc – This directory contains all the configuration files for your system. Your lilo.conf file lies in this directory as does hosts, resolv.conf and fstab.
/home –These are the user home directories, which can be found under /home/username.
/lib – This contains all the shared libraries that are required by system programs. Windows equivalent to a shared library would be a DLL file.
/lost+found – Linux should always go through a proper shutdown. Sometimes your system might crash or a power failure might take the machine down. Either way, at the next boot, a lengthy filesystem check using fsck will be done. Fsck will go through the system and try to recover any corrupt files that it finds. The result of this recovery operation will be placed in this directory.
/mnt – This directory usually contains mount points or sub-directories where you mount your floppy and your CD.
/opt – This directory contains all the software and add-on packages that are not part of the default installation.
/proc – This is a special directory on your system.
/root – We talked about user home directories earlier and well this one is the home directory of the user root.
/tmp – This directory contains mostly files that are required temporarily.
/usr – This is one of the most important directories in the system as it contains all the user binaries. /usr/src/linux contains the source code for the Linux kernel.
/var – This directory contains spooling data like mail and also the output from the printer daemon. The above content briefs about Linux and the file system of Linux.
BASIC COMMANDS IN UNIX
EX. NO. :
DATE
:
AIM: To study the basic commands in UNIX.
COMMANDS:
1. TASK : To display the system date and time.
COMMAND : date.
SYNTAX : date.
EXPLANATION: This command displays the current system date and time on the
screen.
OUTPUT :
2. TASK : To display the current month.
COMMAND : date.
SYNTAX : date +%m.
EXPLANATION: This command displays the current month on the screen.
OUTPUT :
3. TASK : To display the name of the current month.
COMMAND : date.
SYNTAX : date +%h.
EXPLANATION: This command displays the name of the current month on the
screen.
OUTPUT :
4. TASK : To display the current system date.
COMMAND : date.
SYNTAX : date +%d.
EXPLANATION: This command displays the current system date on the screen.
OUTPUT :
5. TASK : To display the current system date (year).
COMMAND : date.
SYNTAX : date +%y.
EXPLANATION: This command displays the current year on the screen.
OUTPUT :
6. TASK : To display the current system time.
COMMAND : date.
SYNTAX : date +%H.
EXPLANATION: This command displays the current system time (in hours) on the
screen.
OUTPUT :
7. TASK : To display the current system time.
COMMAND : date.
SYNTAX : date +%M.
EXPLANATION: This command displays the current system time (in minutes) on the screen.
OUTPUT :
8. TASK : To display the current system time.
COMMAND : date.
SYNTAX : date +%S.
EXPLANATION: This command displays the current system time (in seconds) on the screen.
OUTPUT :
9. TASK : To display the calendar of the current month.
COMMAND : calendar.
SYNTAX : cal.
EXPLANATION: This command displays the calendar of the current month on the
screen.
OUTPUT :
10. TASK : To display user-defined message.
COMMAND : echo.
SYNTAX : echo “message”.
EXPLANATION: This command displays on the screen the argument of the echo
command.
OUTPUT :
11. TASK : To display the details of all users.
COMMAND : who.
SYNTAX : who.
EXPLANATION : This command lists the information about all the users who have
logged on to that system.
OUTPUT :
12. TASK : To display the user detail.
COMMAND : who.
SYNTAX : whoami.
EXPLANATION : This command displays information about the current user of the
system on the screen.
OUTPUT :
13. TASK : To create a directory.
COMMAND : make directory.
SYNTAX : mkdir.
EXPLANATION : This command is used to create a new directory with the specified
name.
EXAMPLE :
OUTPUT :
14. TASK : To change directory.
COMMAND : change directory.
SYNTAX :
cd directory name.
EXPLANATION : This command is used to switch from one directory to another.
EXAMPLE :
OUTPUT :
15. TASK : To delete a directory.
COMMAND : remove directory.
SYNTAX :
rmdir directory name
EXPLANATION : This command is used to delete the specified directory.
EXAMPLE :
OUTPUT :
16. TASK : To come out of a sub-directory.
COMMAND : change directory.
SYNTAX : cd ..
EXPLANATION : This command helps in switching to the main directory.
OUTPUT :
17. TASK : To list all the files and directories.
COMMAND : list.
SYNTAX :
ls.
EXPLANATION : This command displays all the files and directories of the system.
OUTPUT :
18. TASK : To create a file.
COMMAND : cat.
SYNTAX :
cat> file name.
EXPLANATION : This command leads to the creation of a new file with the specified
file name and contents.
EXAMPLE :
OUTPUT :
19. TASK : To view a file.
COMMAND : cat.
SYNTAX :
cat file name.
EXPLANATION : This command displays the contents of the specified file.
EXAMPLE :
OUTPUT :
20. TASK : To copy a file.
COMMAND : copy.
SYNTAX :
cp sourcefile destinationfile.
EXPLANATION : This command produces a copy of the source file and is stored in
the specified destination file by overwriting its previous
contents.
EXAMPLE :
OUTPUT :
21. TASK : To move a file.
COMMAND : move.
SYNTAX :
mv sourcefile destinationfile.
EXPLANATION : After moving the contents of the source file into destination file,
the source file is deleted.
EXAMPLE :
OUTPUT :
22. TASK : To display / cut a column from a file.
COMMAND : cut.
SYNTAX :
cut –c no. filename.
EXPLANATION : This command displays the characters of a particular column in the
specified file.
EXAMPLE :
OUTPUT :
.
23. TASK : To delete a file.
COMMAND : remove.
SYNTAX :
rm file name.
EXPLANATION : This command deletes the specified file from the directory.
EXAMPLE :
OUTPUT :
24. TASK : To retrieve a part of a file.
COMMAND : head.
SYNTAX :
head –no. of rows file name.
EXPLANATION : This command displays the specified no. of rows form the top
of the specified file.
EXAMPLE :
OUTPUT :
25. TASK : To retrieve a file.
COMMAND : tail.
SYNTAX : tail –no. of rows file name.
EXPLANATION : This command displays the specified no. of rows form the bottom
of the specified file.
EXAMPLE :
OUTPUT :
26. TASK : To sort the contents of a file.
COMMAND : sort.
SYNTAX :
sort file name.
EXPLANATION : This command helps in sorting the contents of a file in ascending
order.
EXAMPLE :
OUTPUT :
.
27. TASK : To display the no. of characters in a file.
COMMAND : word count.
SYNTAX :
wc file name.
EXPLANATION : This command displays on the screen the no. of rows, words, and
the sum of no. of characters and words.
EXAMPLE :
OUTPUT :
28. TASK : To display the calendar of a year.
COMMAND : cal.
SYNTAX :
cal year.
EXPLANATION : This command displays on the screen the calendar of the specified year.
EXAMPLE :
OUTPUT :
Listing Directory Contents
1. Log in to the system.
2. Issue the command pwd . What is the path?
________________________________________________________________________
3. Issue the command ls. What do you observe?
________________________________________________________________________
4. Issue the command ls –l . In an abbreviated form, what do you observe?
________________________________________________________________________
________________________________________________________________________
5. Issue the command ls –a. In an abbreviated form, what do you observe?
________________________________________________________________________
________________________________________________________________________
6. Issue the command cd /var.
7. Issue the command pwd . What is the path?
________________________________________________________________________
8. Issue the command ls. What do you observe?
________________________________________________________________________
9. Issue the command ls –l . In an abbreviated form, what do you observe?
________________________________________________________________________
10. Issue the command ls –a. In an abbreviated form, what do you observe?
________________________________________________________________________
11. Issue the command ls – i . Record the inode value for each file and directory. inode filename inode filename
________________________________________________________________________
________________________________________________________________________
Root
In your own words, explain the meaning of:
1. The Root
________________________________________________________________________
2. Administrator Root
________________________________________________________________________
3. Home directory Root
________________________________________________________________________
4. Group Root
________________________________________________________________________
5. What is the difference between the user root and group root.
________________________________________________________________________
- Beside the UNIX commands below, define what each command does.
cd |
pwd |
ls |
cp |
echo |
rm |
mkdir |
rmdir |
Frequently used UNIX commands
Command | Result | ||||
ls | lists files in current working directory | ||||
ls *.out | lists all files in current directory that end in .out | ||||
ls -l | lists files giving details including file size | ||||
pwd | displays full-path name of your current working directory on screen (stands for “present working directory”) | ||||
cd dirname | changes directory to dirname | ||||
cd .. | changes directory to one above the current directory | ||||
cd | with no argument, takes you to your home directory | ||||
mkdir dirname | creates new directory dirname | ||||
rmdir dirname | removes empty directory dirname | ||||
cp filename newname | makes a copy of filename with the name newname | ||||
cp ../filename . | copies filename in directory one tier above to current directory giving it the same name | ||||
mv filename newname | renames filename to newname (mv stands for “move”) | ||||
cat filename | displays contents of filename on screen | ||||
more filename | displays filename contents one screen at a time (Enter key scrolls through file by line; space bar scrolls through by screen) | ||||
head filename | displays first 10 lines of filename on screen | ||||
tail filename | displays last 10 lines of filename on screen | ||||
rm filename | deletes filename without double check (rm stands for “remove”) |
||||
grep string filename | displays lines from filename containing string on screen | ||||
./ filename & | runs job filename in the background | ||||
qsub filename | sends job filename to queue (where qsub is a submission script file in your bin directory) | ||||
qstat | lists jobs running on queue | ||||
qstat -a | lists only your jobs | ||||
qdel job# | deletes job with number job# from queue | ||||
ps | lists processes you have running | ||||
ps -ef | lists all processes | ||||
kill pid# | kills process with ID number pid# | ||||
kill -9 pid# | kills (with the “sure kill” signal) process with ID number pid# | ||||
kill -kill 0 | kills all processes you have running and logs you off | ||||
man commandname | displays manual page for command commandname | ||||
man -k keyword | lists manual pages for commands related to keyword | ||||
lp filename | prints filename on printer in room 4241 | ||||
chmod ### filename | changes “read, write, execute” mode of filename Example: to set the privileges for filename so that the owner has the ability to read, overwrite and execute the file, the group has the ability to read and execute the file, and everyone else has no access to the file, use the command chmod 750 filename. |
||||
owner |
group |
all |
|||
rwx |
rwx |
rwx |
|||
4 2 1 |
4 2 1 |
4 2 1 |
|||
sum numbers for each of the three categories of user | |||||
Ctrl+c | kills current operation | ||||
Ctrl+h | delete (always works even when delete key doesn’t) | ||||
Ctrl+d | logout |
UNIX: vi Editor
EX. NO. :
DATE :
AIM: To study the basic of vi Editor.
UNIX: vi Editor
General Introduction
The vi editor (short for visual editor) is a screen editor which is available on almost all Unix systems. Once you have learned vi, you will find that it is a fast and powerful editor. vi has no menus but instead uses combinations of keystrokes in order to accomplish commands.
There are three basic modes of vi:
Command mode
This is the default when you enter vi. In command mode, most letters, or short sequences of letters, that you type will be interpreted as commands, without explicitly pressing Enter
. If you press Esc when you’re in command mode, your terminal will beep at you. This is a very good way to tell when you’re in command mode.
Insert mode
In insert mode, whatever you type is inserted in the file at the cursor position. Type a (lowercase letter a, for append) to enter insert mode from command mode; press Esc to end insert mode, and return to command mode.
Line mode
Use line mode to enter line oriented commands. To enter line mode from command mode, type a colon ( : ). Your cursor moves to the bottom of the screen, by a colon prompt. Type a line mode command, then press Enter. Any sensible command from the Unix line editor ex will work, and a few are good to know about. These commands are indicated in this handout by a colon in front of the command. Each time you use a line mode command, you must type a colon to enter line mode, then type the command by the colon prompt at the bottom of the screen, then press Enter when you finish typing the command. (The search commands starting with / and ? work similarly.
- are case sensitive – lowercase and uppercase command letters do different things
- are not displayed on the screen when you type them
- generally do not require a Return after you type the command.
Command |
Function |
i | Inserts text to left of the cursor. Existing text shifted right |
I | Inserts text at beginning of line. Existing text shifted right |
a | Appends text to right of the cursor. Existing text shifted right |
A | Inserts text at end of the line |
o | Opens a line below the current line the cursor is on |
O | Opens line above the current line the cursor is on |
rch | Replaces a single character (ch) under cursor. No [Esc] required |
R | Replaces text from cursor to right. Existing text overwritten |
s | Replaces character under cursor with any number of characters |
S | Replaces entire line that cursor is on |
To exit input mode, you must enter the [Esc] key.
Last-line commands used to communicate with the UNIX/Linux shell:
Command | Function |
:w | Writes file to hard drive and remains in editing mode |
😡 | Writes file and quits editing mode |
:wq | Writes file and quits editing mode |
:q | Quits editing mode with no changes made to file |
:q! | Forces vi to quit and exits to the command-line shell |
:w >> note1 | Appends current file contents to new file, note1 |
:r <filename> | Reads contents of <filename> into current vi file |
:n1, n2w customer.sql | Writes selected lines, n1 through n2, to customer.sql |
:.w customer.sql | Writes current line [.] to file, customer.sql |
:$w customer.sql | Writes last line [$] to file, customer.sql |
:! | Used to execute a shell command without leaving vi |
[Crtl-z] | Suspends current session and escaped to UNIX shell |
The linux Story
( after entering the above information, write and quit vi by :wq! )
2. At the moment we need to create a new directory and then change to it. Issue the command:
Then change to the /lab directory.
Prompt: ____________________________________________________________
Full working Path: ____________________________________________________
4. Issue the command touch testfile.
5. Issue the command ls –l testfile. Record the results of the display.
Filename: ___________________________________________________________
File Attributes: ________________________________________________________
File Owner: ___________________________________________________________
File Group: ___________________________________________________________
File Size: _____________________________________________________________
File Creation Date: _____________________________________________________
IP Address: {your system IP address}
I am a great student and am working hard to prove myself as
9. Enter the command ” :w “. This saves the text to the hard drive.
10. Enter the command ” :q “. This exits the vi editor.
11. Enter the command vi testfile3.
IP Address: {your system IP address}
My classmates are great people too.
13. List the contents of the directory. Record the results.
2. What is the path? ______________________________________________
3. Change to the /lab directory ( create the lab directory)
4. Record the full path of the directory. (if it is not /lab, you made an error)
________________________________________________________________________
5. Using the vi text editor, create a new file called test1.
6. Insert into the test1 file the following:
7. Save the file (look at the bottom of the screen to WriteOut the file). Then exit.
8. Using the vi text editor, create a new file called test2.
9. Insert into the test2 file the following:
11. Issue the command cat test1 . Record what you observe.
________________________________________________________________________
12. Issue the command cat test2 . Record what you observe.
__________________________________________________________
13. Issue the command cat test1 test2 . Record what you observe.
________________________________________________________________________
14. Issue the command more test1 . Record what you observe.
________________________________________________________________________
________________________________________________________________________
16. Issue the command less test2 . Record what you observe.
________________________________________________________________________
18. Issue the command history | head . Record what you observe.
________________________________________________________________________
19. Issue the command history | tail . Record what you observe.
________________________________________________________________________
20. Issue the command history | tac . Record what you observe.
________________________________________________________________________
21. Issue the command cat > test3 and hit ENTER.
22. Enter the following lines:
Created using the cat command.
{on this line, enter a CTRL-D}
23. Display the file with the cat command, record your observations.
________________________________________________________________________
1. Test to see if the two files (test1 and test2) may be displayed by different display utilities.
2. Compare the differences between the output of the following:
Moving One Character at a Time
h left one space l right one space
j down one space k up one space
Moving among Words and Lines
w moves the cursor forward one word
b moves the cursor backward one word (if in the middle of a
word, b will move you to the beginning of the current word).
e moves to the end of a word.
Shortcuts
Screen Movement
To move the cursor to a line within your current screen use the following keys:
H moves the cursor to the top line of the screen.
M moves the cursor to the middle line of the screen.
L moves the cursor to the last line of the screen.
To scroll through the file and see other screens use:
ctrl-f scrolls down one screen
ctrl-b scrolls up one screen
ctrl-u scrolls up a half a screen
ctrl-d scrolls down a half a screen
Moving by Searching
Deleting (or Cutting) Characters, Words, and Lines
x deletes the character under the cursor.
X deletes the character to the left of your cursor.
dw deletes from the character selected to the end of the word.
dd deletes all the current line.
D deletes from the current character to the end of the line.
Pasting Text using Put
Copying Text with Yank
yw copies a word into a buffer (7yw copies 7 words)
yy copies a line into a buffer (3yy will copy 3 lines)
Replacing or Changing Characters, Words, and Lines
r replaces the current character with the next character you enter/type.
Once you enter the character you are returned to command mode.
R puts you in overtype mode until you hit ESC which will then return
you to command mode.
cw changes and replaces the current word with text that you type. A dollar
sign marks the end of the text you're changing. Pressing ESC when you
finish will return you to command mode.
Inserting a Blank Line
Appending Text
Joining Lines
Undoing
u undoes the last change you made anywhere in the file. Using u again
will "undo the undo".
U undoes all recent changes to the current line. You can not have moved
from the line to recover the original line.
Closing and Saving Files
Quitting and Saving a File
:w to save your file but not quit vi (this is good to do periodically in
case of machine crash!).
:q to quit if you haven't made any edits.
:wq to quit and save edits (basically the same as ZZ).
Quitting without Saving Edits
:e! reads the original file back in so that you can start over.
:q! wipes out all edits and allows you to exit from vi.
- A shell script is a file containing a list of commands to be executed by the Linux shell. shell script provides the ability to create your own customized Linux commands
- Linux shell have sophisticated programming capabilities which makes shell script powerful Linux tools
Where vi is the editor ,it will open a new window in which you can type the program you want
Sh – command is used to run the shell program
<file name> – is the name of the file for which the output is to be got
Basically to print a text in the your shell programs echo command is used
4. LOGNAME is the variable that holds your username.
5. MAIL provides UNIX with an absolute path to each user’s mailbox. Determine your MAIL settings.
7. PS1 is the primary prompt string for the shell. Determine your PS1 settings
- TERM is the variable that indicates the type of terminal you are using. Determine your TERM setting.
For(( intitialization;condition;incremetation/decrementation))
AREA OF THE TRIANGLE
To write a shell script to find the area of the triangle
Step1 : get the base and height
SQUARE OF THE NUMBER
To write a shell script which accepts a number less than 50 and display its square
Step2 : Check if the number is less than 50. If the number is less than 50 then compute
ODD NUMBER GENERATION
To write a shell script display a list of odd numbers below a given number
Step3 : Display the list of odd numbers by incrementing count by 2 until the given limit.
To write a shell script to print the Fibonacci series
Step2 : add the first two numbers to produce the third number
Step3 : add the second and third number to get the fourth number and so on
Step3 : if the average is greater than 75 then assign grade as “Distinction”
if the average is between 60 to 75 then assign grade as “First Class”
if the average is between 50 to 59 then assign grade as “Second Class”
else then assign grade as “Fail”
VOWEL OR NOT
To write a shell script to find whether a given character is vowel or constant
Step2 : If it matches with any of the vowels a,e,i,o,u print it as vowel
Step3 : Otherwise print it as a constant
To write a shell script for a menu driven program.
Step1 : Get the option, use case statement to display the various functions
Step2 : first option to view the content of the home directory
Second option to list the users who have logged
Third option to print the present working directory
Fourth option to count the words, characters and lines of a file
Fifth option to print the type of file
Step3 : Display the result according to the option chose
PALINDROME CHECKING
To write a shell script to check whether the given string is a palindrome or not
Step2 : find the length of the string
Step3 : extract the input string into another variable starting from the last character
Step4 : check whether the input string and the reversed string are the same
Step5 : if so, display “given string is a palindrome” else display “given string is not
USER LOGGED IN OR NOT
To write a shell script to accept the name of the user and check out if the user has
Step1 : accept username from command line
Step2 : use ‘grep’ filter ,extract username from /dev/null file
Step3 : check whether the input username is in the /dev/null file
.If the username is present in
the file,display message as “user has logged in”
else, display the message as “user has not logged in”
COUNT THE ORDINARY FILE AND DIRECTORY
Step1 : Read the directory name
Step2 : Check if the number of command line arguments read .
Step3 : If the number of arguments read is less than one, then display the message as
Step4 : Check whether the file is ordinary file or directory file[-f or –d]
Step5 : Using ‘grep’ filter, extract the number of files and directory files in two variables
Step6 : Display the count of files and directory files
DISPLAY THE FILE PERMISSION
Step1 : Accept filenames from command line
Step2 : In a for loop, using the ‘cut’ command extract the file permission from the long
Step3 : Display the filenames and their permission.
To write a shell script to convert the content of given files to uppercase letters
Step1 : Accept filenames to be converted from command line
Step2 : Using the ‘tr’ command to convert the content of file to upper case
Step3 : Display the content of converted files
FILE MANAGEMENT
To write a C program to perform file operations using file descriptor
Step 1: Get file name from user
Step 2: Get the string and find the length of the string
Step 3: Open the file in write mode
Step 4: Write the string in the file
Step 6: Open the file in read mode
Step 7: Read the contents of the file and store it in a temporary storage space
Step 8: Print the buffer contents on the screen
To write a C program to create a new process using fork
Step1 : Create the process using fork() system call
Step2 : Check the process id of current process
Else it is a “parent process” and display the process id of current process and parent process
IMPLEMENTATION OF UNIX COMMANDS
GE2155 CP LAB 2
What is UNIX?
UNIX is an operating system which was first developed in the 1960s, and has been under constant development ever since. By operating system, we mean the suite of programs which make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops and laptops.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which provides an easy to use environment. However, knowledge of UNIX is required for operations which aren’t covered by a graphical program, or for when there is no windows interface available, for example, in a telnet session.
Types of UNIX
There are many different versions of UNIX, although they share common similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X.
The UNIX operating system
The UNIX operating system is made up of three parts; the kernel, the shell and the programs.
The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.
The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt (% on our systems).
The adept user can customise his/her own shell, and users can use different shells on the same machine. Staff and students in the school have the tcsh shell by default.
The tcsh shell has certain features to help the user inputting commands.
Filename Completion – By typing part of the name of a command, filename or directory and pressing the [Tab] key, the tcsh shell will complete the rest of the name automatically. If the shell finds more than one name beginning with those letters you have typed, it will beep, prompting you to type a few more letters before pressing the tab key again.
History – The shell keeps a list of the commands you have typed in. If you need to repeat a command, use the cursor keys to scroll up and down the list or type history for a list of previous commands.
Files and processes
Everything in UNIX is either a file or a process.
A process is an executing program identified by a unique PID (process identifier).
A file is a collection of data. They are created by users using text editors, running compilers etc.
Examples of files:
- a document (report, essay etc.)
- the text of a program written in some high-level programming language
- instructions comprehensible directly to the machine and incomprehensible to a casual user, for example, a collection of binary digits (an executable or binary file);
- a directory, containing information about its contents, which may be a mixture of other directories (subdirectories) and ordinary files.
Basic UNIX Commands
alias Allows you to substitute a preferred name for a UNIX command.
back Move back to the directory you were in before your last cd command.
cat Concatenate an input file to an output file. Can be used to create a new file.
C-d Under cat, tells the program that you are done entering information.
C-q Under cat, tells the program to resume scrolling after a C-s.
C-s -Under cat, tells the program to pause
cd Move to a new directory (change directory).
cp Copy a file to another directory.
head Displays the first ten lines of a file.
jobs Tells you what jobs are in the background.
kill Terminates a background job.
less Similar to more, less displays the contents of a file but allows backwards movement.
b Under less, scrolls back one page.
y Under less, scrolls back one line.
g Under less, jumps back to the start of the file.
G Under less, jumps to the end of the file.
lp Print command that prints output horizontally.
lpstat Shows you how many print jobs are queued to the printer.
ls Displays the contents of a directory.
ls -a Displays files that start with a (.) as well as the rest of the contents of the directory.
ls -l Displays the same files as ls but includes more information.
ls -F Tells whether a file listed in an ls is an executable program, directory, or file.
man Displays short message about a particular UNIX command (e.g. man ls).
mkdir The create directory command.
more Displays the first screen’s worth of a file.
Space Bar Under more, scrolls to the next page.
Return Under more scrolls one line.
q Under more, quits displaying the file and returns to UNIX
mv Move a file from one directory to another.
passwd Change your password.
ps lists out all of the processes that are running on your machine.
pwd Print out the current directory.
rm The remove command for eliminating files.
-r A switch for the rm command that allows you to remove all files and directories in a particular directory, and then remove the directory itself.
rmdir The remove directory command.
Starting vi and Saving Files
vi filename start editing filename, create it if necessary
Saving the file you’re working on and/or leaving vi:
:wq write the file to disk and quit
:q! quit without saving any changes
:w! newfile write all lines from the entire current file into the file ‘newfile’, overwriting any existing newfile
:n,m w! newfile write the lines from n to m, inclusive, into the file newfile, overwriting any existing newfile
Useful vi Commands
Cut/Paste Commands:
x delete one character (destructive backspace) dw delete the current word (Note: ndw deletes n numbered words) dd delete the current line (Note: ndd deletes n numbered lines) D delete all content to the right of the cursor d$ same as above :u undo last command p,P paste line starting one line below/above current cursor location J combine the contents of two lines "[a-z]nyy yank next n lines into named buffer [a-z] "[a-z]p/P place the contents of selected buffer below/above the current line
Extensions to the Above Commands:
:3,18d delete lines 3 through 18 16,25m30 move lines 16 through 25 to after line 30 23,29co62 copy specified lines and place after line 62
Cursor Relocation commands:
:[n] goto line [n] shift g place cursor on last line of text h/l/j/k move cursor left, right, down and up ^f/^b move forward, backward in text, one page ^u/^d move up, down one half page $ move to end of line 0 move to beginning of line
Extensions to the Above:
b move backwards one word (Note: nb moves back n number of words) e move to end of current word ( move to beginning of curent block ) move to the end of current block
Searching and Substitution commands:
/ [string] search forward for string ? [string] search backwards for string n repeat last search N repeat search in opposite direction cw change the contents of the current word, (use ESC to stop replacement mode) c$ Replace all content to the right of cursor (exit replacement mode with ESC) c0 Replace all content to the left of cursor (exit with ESC) :1,$s/s1/s2/g (Yow!) global replacement of string1 with string2 r replace current character with next character typed
Entering the Insert Mode:
i Begin inserting text at current cursor location I Begin inserting text at the beginning of the current line a Begin appending text, one character to the right of current cursor location A Begin appending text at the end of the current line o/O Begin entering text one line below\above current line ESC Exit insertion mode and return to command mode
Exiting and Entering vi
ZZ save file and exit VI :wq same as above :e! return to last saved version of current file :q quit without save, (Note :q! is required if changes have been made) :w write without exit (:w! to force write) Miscellaneous Commands: :1,10w file write lines 1 through 10 to file newfile :340,$w >> file write lines 340 through the end of the file and append to file newfile :sh escape temporarily to a shell ^d return from shell to VI :![command] execute UNIX command without leaving VI :r![command] read output of command into VI :r[filename] read filename into VI :$r newfile read in newfile and attach at the end of current document :r !sort file read in contents of file after it has been passed through the UNIX sort :n open next file (works with wildcard filenames, ex: vi file*) :^g list current line number :set number show line numbers :set showinsert show flag ("I") at bottom of screen when in insert mode :set all display current values of VI variables :set ai set autoindent; after this enter the insert mode and tab, from this point on VI will indent each line to this location. Use ESC to stop the indentations. ^T set the autoindent tab one tab stop to the right ^D set the autoindent tab one stop to the left :set tabstop=n sets default tab space to number n >> shift contents of line one tab stop to the right << shift contents of line one tab stop to the left
Entering Text
To begin entering text in an empty file, you must first change from the command mode to the insert mode. To do this, type the letter i. When you start typing, anything you type will be entered into the file. Type a few short lines and hit Return at the end of each of line. Unlike word processors, vi does not use word wrap. It will break a line at the edge of the screen. If you make a mistake, you can use the Backspace key to remove your errors. If the Backspace key doesn’t work properly on your system, try using the Ctrl h key combination.
Cursor Movement
You must be in command mode if you wish to move the cursor to another position in your file. If you’ve just finished typing text, you’re still in insert mode and will need to press ESC to return to the command mode.
Moving One Character at a Time
Try using your direction keys to move up, down, left and right in your file. Sometimes, you may find that the direction keys don’t work. If that is the case, to move the cursor one character at the time, you may use the h, j, k, and l keys. These keys move you in the following directions:
h left one space l right one space j down one space k up one space
If you move the cursor as far as you can in any direction, you may see a screen flash or hear a beep.
Moving among Words and Lines
While these four keys (or your direction keys) can move you just about anywhere you want to go in your file, there are some shortcut keys that you can use to move a little more quickly through a document. To move more quickly among words, you might use the following:
w moves the cursor forward one word b moves the cursor backward one word (if in the middle of a word, b will move you to the beginning of the current word). e moves to the end of a word.
To build on this further, you can precede these commands with a number for greater movement. For example, 5w would move you forward five words; 12b would move you backwards twelve words. [You can also use numbers with the commands mentioned earlier. For example, 5j would move you down 5 characters.]
Command Keys and Case
You will find when using vi that lower case and upper case command keys are interpreted differently. For example, when using the lower case w, b, and e commands, words will be defined by a space or a punctuation mark. On the other hand, W, B, and E commands may be used to move between words also, but these commands ignore punctuation.
Shortcuts
Two short cuts for moving quickly on a line include the $ and the 0 (zero) keys. The $ key will move you to the end of a line, while the 0 will move you quickly to the beginning of a line.
Screen Movement
To move the cursor to a line within your current screen use the following keys:
H moves the cursor to the top line of the screen. M moves the cursor to the middle line of the screen. L moves the cursor to the last line of the screen.
To scroll through the file and see other screens use:
ctrl-f scrolls down one screen ctrl-b scrolls up one screen ctrl-u scrolls up a half a screen ctrl-d scrolls down a half a screen
Two other useful commands for moving quickly from one end to the other of a document are G to move to the end of the file and 1G to move to the beginning of the file. If you precede G with a number, you can move to a specific line in the document (e.g. 15G would move you to line 15).
Moving by Searching
One method for moving quickly to a particular spot in your file is to search for specific text. When you are in command mode, type a / followed the text you wish to search for. When you press Return, the cursor will move to the first incidence of that string of text. You can repeat the search by typing n or search in a backwards direction by using N.
Basic Editing
To issue editing commands, you must be in command mode. As mentioned before, commands will be interpreted differently depending upon whether they are issued in lower or upper case. Also, many of the editing commands can be preceded by a number to indicate a repetition of the command.
Deleting (or Cutting) Characters, Words, and Lines
To delete a character, first place your cursor on that character. Then, you may use any of the following commands:
x deletes the character under the cursor. X deletes the character to the left of your cursor. dw deletes from the character selected to the end of the word. dd deletes all the current line. D deletes from the current character to the end of the line.
Preceding the command with a number will delete multiple characters. For example, 10x will delete the character selected and the next 9 characters; 10X will delete the 10 characters to the left of the currently selected character. The command 5dw will delete 5 words, while 4dd deletes four lines.
Pasting Text using Put
Often, when you delete or cut text, you may wish to reinsert it in another location of the document. The Put command will paste in the last portion of text that was deleted since deleted text is stored in a buffer. To use this command, place the cursor where you wish the deleted text to appear. Then use p to reinsert the text. If you are inserting a line or paragraph use the lower case p to insert on the line below the cursor or upper case P to place in on the line above the cursor.
Copying Text with Yank
If you wish to make a duplicate copy of existing text, you may use the yank and put commands to accomplish this function. Yank copies the selected text into a buffer and holds it until another yank or deletion occurs. Yank is usually used in combination with a word or line object such as the ones shown below:
yw copies a word into a buffer (7yw copies 7 words) yy copies a line into a buffer (3yy will copy 3 lines)
Once the desired text is yanked, place the cursor in the spot in which you wish to insert the text and then use the put command (p for line below or P for line above) to insert the contents of the buffer.
Replacing or Changing Characters, Words, and Lines
When you are using the following commands to replace text, you will be put temporarily into insert mode so that you can change a character, word, line, or paragraph of text.
r replaces the current character with the next character you enter/type. Once you enter the character you are returned to command mode. R puts you in overtype mode until you hit ESC which will then return you to command mode. cw changes and replaces the current word with text that you type. A dollar sign marks the end of the text you're changing. Pressing ESC when you finish will return you to command mode.
Inserting Text
If you wish to insert new text in a line, first position the cursor to the right of where you wish the inserted text to appear. Type i to get into insert mode and then type in the desired text (note that the text is inserted before the cursor). Press ESC to return to command mode.
Inserting a Blank Line
To insert a blank line below the line your cursor is currently located on, use the o key and then hit ESC to return to the command mode . Use O to insert a line above the line the cursor is located on.
Appending Text
You can use the append command to add text at any place in your file. Append (a) works very much like Insert (i) except that it insert text after the cursor rather than before it. Append is probably used most often for adding text to the end of a line. Simply place your cursor where you wish to append text and press a. Once you’ve finished appending, press ESC to go back to command mode.
Joining Lines
Since vi does not use automatic word wrap, it is not unusual in editing lines to end up with lines that are too short and that might be improved if joined together. To do this, place your cursor on the first line to be joined and type J. As with other commands, you can precede J with a number to join multiple lines (4J joins 4 lines).
Undoing
Be sure to remember this command. When you make a mistake you can undo it. DO NOT move the cursor from the line where you made the change. Then try using one of the following two commands:
u undoes the last change you made anywhere in the file. Using u again will "undo the undo". U undoes all recent changes to the current line. You can not have moved from the line to recover the original line.
Closing and Saving Files
When you edit a file in vi, you are actually editing a copy of the file rather than the original. The following sections describe methods you might use when closing a file, quitting vi, or both.
Quitting and Saving a File
The command ZZ (notice that it is in uppercase) will allow you to quit vi and save the edits made to a file. You will then return to a Unix prompt. Note that you can also use the following commands:
:w to save your file but not quit vi (this is good to do periodically in case of machine crash!). :q to quit if you haven't made any edits. :wq to quit and save edits (basically the same as ZZ).
Quitting without Saving Edits
Sometimes, when you create a mess (when you first start using vi this is easy to do!) you may wish to erase all edits made to the file and either start over or quit. To do this, you can choose from the following two commands:
:e! reads the original file back in so that you can start over. :q! wipes out all edits and allows you to exit from vi.