Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1-Coordinator Guide
NIIT
Linux 1
2 Linux
NIIT
RATIONALE
Why This Module
Linux is often considered an excellent, low-cost alternative to other expensive operating systems It has accelerated the free software movement in the industry The course starts with the history and the architecture of Linux operating system and covers advanced topics that ma!e a student a power user This module is very important for the learner as the fundamental commands li!e ls, cp, rm, and mkdir would "e later used in #$$ This module is important as the student needs to !now a"out creating and maintaining documents using the vi editor in Linux, as he would "e using it to type #$$ programs
NIIT
Linux .
O'%ECTI(E)
The o",ective of this module is to familiari/e students with the Linux platform and provide sufficient !nowledge to ma!e them power users 0s most tas!s in Linux are performed using the shell commands, this module covers various shell commands and utilities that are re&uired while wor!ing on Linux The course also covers implementation of !ey programming concepts covered in %rogramming Logic and Techni&ues
1 Linux
NIIT
ENTR* #RO+ILE
0 student who registers for the Linux module should "e a"le to perform the following tas!s2
3or! in a 3indows-"ased environment - The student will need to connect to Linux through the
Telnet utility 4nowledge of the 3indows interface is re&uired to start Telnet
Interact in 5nglish in a classroom environment - The classes will "e conducted in 5nglish The
courseware will also "e in 5nglish The sessions will "e interactive in nature
NIIT
Linux 6
E ,IT # RO+ILE
0t the end of this module, the students will "e a"le to2
) ills A-.uired
Identifying the features of the Linux operating system Identifying login and logout procedures 7sing a text editor to create and maintain documents 8anaging files on a Linux computer #reating and executing shell scripts 0utomating tas!s using shell scripts #reating glo"al and local varia"les #hanging the shell prompt 0pplying a password to secure a file or folder )ecuring files and directories "y changing file access permissions 5xecute a process in the "ac!ground #alculate timing statistics re&uired to execute a process
9 Linux
NIIT
+A/
:1 01 3hat is ;ed <at Linux= )ince the Linux !ernel 'currently maintained "y Linus Torvalds( is availa"le free, many distri"utions "undle the !ernel with shells and add their own tools and utilities ;ed <at, Inc is one of the leading and most popular distri"utors for Linux There are several other distri"utions of Linux such as #aldera, >e"ian, 8andra!e, easyLinux, )lac!ware, and )u)5 ;ed <at, Inc has contri"uted a lot of good tools for administering Linux Is there any office suite in Linux= The two most popular office suites are )tar*ffice and 0pplixware 8ore information on them can "e found from their respective 3e" sites The following 3e" sites should "e noted2
:2 02
:1 01
http://www.plug.org http://www.linux-india.org/ http://www.ilug-bom.org/ http://www.linux-india.org/chapters.shtml ? This page provides a list of the L7@s availa"le
in India :6 06 <ow did Linux evolve= The origin of free software started from the need of universities to "e a"le to share information and to allow students and developers to adapt software to their needs In 1BC1, ;ichard )tallman, a researcher at the 8IT 0I La", started a pro,ect, @N7, to counter the fast-moving trend toward proprietary, fee-"ased software This concept served as the "asis of Linux development Linus
NIIT
Linux D
Torvalds, a student at the 7niversity of <elsin!i, "egan developing Linux in 1BB1, and originally targeted Linux at the Intel .C9 Torvalds wanted to write a new version of 7nix, so he and a group of programmers com"ined talents and created a core operating system called Linux 0 large num"er of volunteer developers wor!ed on the !ernel The information was shared over the Internet, and created a community that supported each other :9 09 :D 0D >oes open source and Linux mean the same= No The open source movement aims at !eeping the software source code open and accessi"le to all *pen source software includes the Linux software )ince Linux is free, how do companies selling Linux earn revenue= Traditionally, license fees have "een the main source of revenue for the software industry #ompanies selling Linux, such as ;ed <at, usually earn from the support and training they provide to their clients
C Linux
NIIT
NOTE
+OR
+AC0LT*
Aou should have solved all the pro"lems in the )tudent @uide "efore the start of the module ;emem"er that the student is new to Linux and is wor!ing first time on the command line interface The student may face pro"lems with the syntax of the commands It is crucial that you encourage students to try out all the commands given in the student guide on the Linux operating system The student must try out the examples and code given in the "oo! on the computer Aou must aim for the following2
The student is comforta"le with the command line interface of Linux The student appreciates the features of the Linux operating system The student is comforta"le with the vi editor as it is extensively used in the **%s module The student is encouraged to use the man and info pages
It is faster to complete tas!s using the command line interface The advantage of executing commands in the command line interface should "e explained to the students
NIIT
Linux B
1 OW
TO IN)TALL T1E
) CRI#T)
The sem1.tar.gz file present on the T;8-#> under the shellscripts folder contains the scripts re&uired for the Linux module 7se the following steps to install the scripts2 1( Log in to the Linux system as root user 2( Insert the T;8-#> into the #>-;*8 drive and mount the T;8-#> using the following command2 mount /mnt/cdrom .( #reate a directory /root/sem1 mkdir /root/sem1 1( #hange your current directory to the +root+sem1 cd /root/sem1 6( #opy the sem1 tar g/ file present on the T;8-#> into the /root/sem1 directory cp /mnt/cdrom/shellscripts/sem1.tar.gz /root/sem1 9( ;estore the files from the "ac!up using the following command2 tar -zxvf sem1.tar.gz Aou are through with the installation of scripts 0ppropriate directories would get created Aou would have to change to the appropriate directory to execute the scripts The EConfiguring the ResourceE section in the #@ explains the script to execute for different lessons
Note
In case you do not have a #>-;*8 drive "ut have a floppy drive, copy the sem1.tar.gz file from the T;8-#> into a floppy on a 3indows machine Then insert the floppy into the floppy drive of the Linux server To use the floppy, you would have to mount the floppy drive To mount the floppy drive that supports long file names, use the following command2 mount -t vfat /dev/fd0 /mnt/floppy. Aou can also use FT% to transfer the file to the Linux server 7se "inary mode to transfer the file 0fter you have installed the scripts, you should get the following directories created2 common mrwee!2 and mrwee!. These directories contain scripts and data files that are needed for demonstration and practice
1G Linux
NIIT
Aou need to change to the common directory where you will find seven very important scripts2 1( createmrusers2 5xecute this script to create machine room users2 user1, user2, user.H user.G This script needs to "e run when the Linux server is installed 2( createocruser2 5xecute this script to create online classroom users2 ocruser1, ocruser2, H ocruser16 and a login for faculty This script needs to "e run when the Linux server is installed .( delpassmr2 5xecute this script if you want to clear passwords created "y some students on the user logins 1( delpassocr2 5xecute this script if you want to clear the passwords on the the ocruser accounts 6( clearmr2 5xecute this script to delete all the files in the +home+user1, +home+user2, H +home+user.G directories These are the home directories of the machine room users This would also delete any su"directories the users may create 9( clearocr2 5xecute this script to delete all the files in the +home+user1, +home+user2, H +home+user.G directories These are the home directories of the ocr users 3hen the students are going to wor! on the Linux server in the 8achine room, they should log in as user1, user2 user.G 3hen the students are going to wor! on the Linux server in the *#;, they should login as ocruser1, ocruser2,H ocruser16 #onfiguring the ;esource for the 8;2
Module Week number Script to be executed Location of the scripts, when the scripts are installed in the /root/sem1 directory /root/sem1/mrweek1 /root/sem1/mrweek2 No script needs to be executed
MR MR MR
1 2 3
NIIT
Linux 11
)O0RCE)
1 2 .
O+
IN+ORMATION
@o through the <*3 T* documents extensively They provide a wealth of information for performing tas!s There are plenty of such documents, so read only the ones that are essential For any command, go through the man and info pages @o through the ;ed <at site, http://www.redhat.com Aou will find a lot of documentation on Linux The "oo!s released "y ;ed<at, such as Installation Guide and Getting Started are good, and are availa"le free at the site 'they are also availa"le on the ;ed <at Linux #>( The Search option availa"le on the ;ed <at site is also useful In addition, go through the F0:s archived there
12 Linux
NIIT
If you donJt li!e 3indows Telnet, you can download any good free Telnet software from the
Internet *ne good Telnet utility is the Tera Term software availa"le at the following 7;L, http://hp.vector.co.jp/authors/VA00241 /teraterm.html
Aou can also download a very good utility called putty, which is a free telnet software from
http2++www chiar! greenend org u!+Ksgtatham+putty+ This utility gives a full screen view and does not have pro"lems of refreshing the screen faced sometime in 3indows telnet utility
5xecute the script mrwee!1 "efore starting with the unguided practice session
NIIT
Linux 1.
Additional In2uts
3hen you are teaching students a"out the concepts of a multi user environment, you can tell them how multiple users can log on to the server Tell them that 3indows NT is actually not a multi user system, as multiple users cannot wor! on the system simultaneously 3indows NT Terminal )erver edition is actually a multi user system Linux supports the following types of special files2
#haracter device files Iloc! device files <ard lin!s )ym"olic lin!s
"haracter#device#$iles read and write data one character at a time 0 modem is an example of a character device file #haracter devices are also called se&uentially-accessed devices %loc!#device#$iles can access a "loc! of data at a time @enerally, a "loc! of data can "e either 612 or 1,G21 "ytes <ere, the !ernel reads or writes a minimum of one "loc! of data at a time The !ernel collects the data in the memory for the amount of "loc! memory and then ma!es it availa"le to a user )uch devices allow random access This ma!es input+output operations faster 0n example of a "loc! device is the hard dis! 8any of the devices can act as character devices or "loc! devices depending on the command that is used to access the device
Note
In operating systems such as Linux, there are two types of data stored on the dis!, the meta data and the actual data The actual data is the physical contents of a file 8eta data is the data pertaining to a fileJs location in the filesystem and all its other attri"utes, such as the owner, the permission, and the type of the file The data a"out the entire Linux operating system is maintained as a set of index nodes or inodes These inodes contain pointers to the meta data, which in turn contain pointers to the physical data on the dis! 5ach file in the filesystem has an inode and is identified "y an inode num"er ' i-number( Note that each partition on the hard dis! maintains its own filesystem The inodes are created when a filesystem is created There are a set num"er of inodes, which indicate the maximum num"er of files the Linux operating system can hold 0 fileEs inode num"er can "e found using the ls -i command, while the ls -l command will retrieve inode information &ard#lin!s are special files that allow a single file to have multiple names Aou can have a hard lin! file only for a file and not for a directory These lin!s are !nown as hard lin!s "ecause they create a direct lin! to an inode )ince each filesystem has its own inode information data"ase, you can hard-lin! files only when they are on the same filesystemL sym"olic lin!s 'see "elow( donEt have this restriction '(mbolic#lin!s, also !nown as so$t#lin!s, are similar to hard lin!s except that they can wor! across different filesystems The ~ sign refers to a userJs home directory The solutions for most of the exercises refer to the home directory as K for reducing any !inds of errors For example, the command, ls l ~, lists the contents
11 Linux
NIIT
of the current userJs home directory In case you want to create multiple directories, you can specify them in the same m!dir command For example, $mkdir dira dirb would create two directories In case you want to create a su"-directory, and its parent directory does not exist, you can specify the -p option with the mkdir command so that the entire directory tree gets created For example, $mkdir -p grandfather/father/son This command would create the grandfather, father, and son directories if they do not exist
01 The mv command 'mv ~/ ustomer alls/!eports/" ~/#ld!eports( 2 >etails a"out the products and services offered at >ia/ Telecommunications, Inc are stored in the file, ,roducts.txt, present under the /-ia./'ervices directory Aou need a copy of this file in your home directory 3hich command will you use=
02 The cp command 'cp /$iaz/%ervices/&roducts.t't ~( . The command to move all the files that start and end with a vowel from your home directory into the su"-directory named Trial present under your home directory will "e2 mv K+ Maeiou05I*7NOMaeiou05I*7N K+Trial The ls command is used to list all the files under your wor!ing directory 3hat are wildcards= 06 3ildcards are characters used to group multiple files Files can "e grouped to perform actions, such as copying, moving, and deleting 9 D The (list) wildcard is used to match any one pattern from a list 3hat is the maximum num"er of characters that can "e used in a file name= 0D 269 characters
1 6
0n!uided #ra-ti-e
Con3i!urin! the Resour-e
All the students must connect to the Linux server for the Unguided Practice. You must execute the script /root/sem1/mrweek1/mrweek1 to configure the student logins. You should !e logged in as the root user to execute the script.
NIIT
Linux 16
cd /etc p*d ls /etc ls /etc/".conf man cp cd ~ mkdir -p ./sales/trends ./sales/bills ./products ./info/remote ./info/local cp /home/customer/" ~ more /var/log/dmesg less ~/cust-details $ cp ".sh ./info/remote/ $ ls ./info/remote/
h+ i+ ,+ k+
l+ m+ n+
19 Linux
NIIT
Lesson T"o
Ex2erien-es
The need for pipes and filters should "e discussed when you solve any of the pro"lem statements >iscuss the options availa"le of the various filters 5xplain changing F0%s "oth with sym"ols and num"ers 3hen the first demonstration in this lesson, 2 > 1 implemented using the find / -name dmesg -e'ec cat ./01 the contents of the result would scroll up 0fter explaining the pipes and redirection concept you can again execute the command as2 find / -name dmesg -e'ec cat ./ 01 23 err, to redirect error messages to an error file Aou can also enter4 find / -name dmesg -e'ec cat ./ 01 5 less to view the contents of the file page wise In the "eginning, students will not "e very comforta"le using the vi editor 3hile giving the demo for the vi editor, you must patiently explain the difference "etween the command mode and the insert mode of the vi editor Tell the students that operating systems have an editor software, which allows you to edit and save text files For example, 3indows B6+BC+NT ? Notepad 8)->*) ? 5dit 7nix ? vi These editors usually do not have text formatting capa"ilities "ecause they are mostly used for editing the system configuration files and creating scripts They are also more compact and faster than "ul!y word processors '8icrosoft 3*;>, )tar*ffice )tar3riter( If a student wants to enter the world of Linux-"ased software development or Linux system administration, fluency with such an editor is imperative It is a good idea to teach students several extra commands in the vi editor, as they are expected to wor! on it throughout while programming in #$$ Aou must ensure that students en,oy wor!ing on vi and understand the rationale and advantages 'speed and flexi"ility( of using the vi editor
NIIT
Linux 1D
next until the oil is completely refined Note that the flow is only in one direction The same is true for the pipes in Linux Linux pipes also receive data from one end and send it to another, o"livious of the origin and the destination of the data Aou can relate to the vi editor with the note"oo! that we all carry 3e write our notes on the "oo! using a pen In this case, we can use the vi editor to write our notes to a computer file
+A/
:1 3hy are pipes and filters always discussed together= 01 0lthough pipes and filters are two different utilities, they are usually discussed in the same context This is "ecause, they are mostly used together Filters ta!e input from the standard input It is a common practice to pass the output of a pipe to a filter :2 3hat is the default permission when a file is created= 02 The umask value determines the initial file permissions on a newly created file The value of umask is turned off from the mode value, which is 999 for files and DDD for directories and executa"le files The mode value indicates that all the users have read and write permissions for a file Iy default, the umask value is given as GG2 for a normal user and G22 for the root user, which means that every file that an ordinary user creates has the permission, 999 ? GG2 P 991 'rw-rw-r--( 0s you notice, the user and the group have the write permission Iy default, the primary group of the user is the group owner of all the files that the user creates The umask value of G22 will prevent users from modifying other usersJ private files The umask value is set in the /etc/pro$ile file :. <ow can the owner of the file "e changed= 0. The owner of the file can "e changed using the cho*n command :1 <ow can the group owner of a file "e changed= 01 The group owner of a file can "e changed using the chgrp command :6 3hat is vim= 06 vim stands for vi#improved It is an extension of the vi editor It has several added features For further information on the vim editor, refer to the 3e" site www.vim.org :9 3hy vi editor= It is too difficult to wor! on it 09 vi is extremely popular, not "ecause it is the oldest editor availa"le in the 7nix environment "ut "ecause it is one of the fastest editors In fact, there is also a vi editor for 3indows, which is "ecoming popular The vim editor has a lot of added features and is very flexi"le to use :D 3hich is the most popular editor on Linux= 0D The two most popular editors are vi and 5macs 3hich is "etter or more popular is a &uestion that no"ody can answer If you visit any newsgroup or forum, you will definitely find more than one discussion on this issue 5macs is not only a text editor "ut has many other features and can "e used as a N53) reader, a mail client, and ,ust a"out anything else The Q 3indow )ystem version of 5macs is popular and easy to use The other popular editor on Linux is the -oe editor :C 3hat is 5macs=
1C Linux
NIIT
0C 5macs was written "y ;ichard )tallman 'who is the founder of the Free )oftware Foundation and the @N7 pro,ect( and he still maintains it 5macs is one of the most popular and powerful text editors used on Linux 'and 7nix( It is !nown for its huge feature set, a"ility to "e easily customi/ed, and lac! of "ugs Its large feature set and a"ility to "e customi/ed are actually the result of how it was designed and implemented 5macs isnEt ,ust an editor It is written mostly in the programming language, Lisp 0t the core of 5macs is a full-featured Lisp interpreter written in # )o, in a sense, 5macs has an entire programming language "uilt in which you can use to customi/e, extend, and change its "ehavior 5macs is used as a text editor, a mail client, a N53)-reader, an integrated development environment, and is highly customi/a"le ;efer to the 3e" site, http://www.gnu.org/so$tware/emacs/emacs.html+, for further information on 5macs :B Is there a 3indows version for the vim editor= 0B Aes, there is a 3indows version of the vim editor Further information can "e o"tained from the 3e" site, www.vim.org. :1G 3hat is the difference "etween the less and the more filter= 01G The more filter is not capa"le of scrolling upwards whereas the less filter can scroll in "oth directions, up and down The less filter is also faster than the more filter The more filter still exists "ecause of legacy reasons as the previous version of 7nix had only the more utility and not less :11 3hy is the filter less faster than the filter more= 011 This is "ecause the filter less accepts data and caches the data )ince the less filter caches the data in the memory, moving up and down a page is possi"le and is faster
3hat are the methods for securing your personal files and folders=
02 %assword, F0%, loc!ing the wor!station, and password protection . 1 The numeric e&uivalent of the read permission is 4 3hat permissions are availa"le if a file has "een assigned D66 as F0%=
01 0ll permissions for file owner, read and write permission for group users and other users 6 Find the location of the file exports on your Linux server
09 cat /etc/pass*d 5 cut -d848 -f1 D %redict the output of the following command2 ls l 5 tr s 8 8 5 cut d 8 8 f9:;
NIIT
Linux 1B
0D The command will display the si/e and the names of all the files in the current directory C B The command to display the num"er of users currently logged in to the Linux computer is who | wc l The tr filter is used to replace a character with another character
1G 3hat are the differences "etween the more and less filters= 01G The more filter supports forward scaling only, whereas, the less filter supports forward and "ac!ward scaling 11 %redict the output of the following command2 cat <rial 5 tr 8(a-z)8 8(=->)8 011 The contents of the file <rial will "e displayed as uppercase letters
Additional In2uts
)ome more interesting utilities in Linux and their usage are as follows2
semicolon
ampersand
The most common way of informing the shell that a command has ended is the newline character This is inserted on pressing the "#nter$ !ey
Exa42le
$ pwd < nter! /home/%teve ?ne*line+
The semicolon '1( can "e used to terminate commands This is useful when you want to write several commands on the same line
Exa42le
$ date"who | wc -l" pwd < nter! @on #ct A 0049B4AB C%< 1;;; 2 /home/%teve The "#nter$ !ey has to "e pressed after entering the se&uence of commands In the a"ove command, *ho 5 *c l is executed after date, and p*d after *ho 5 *c -l This is identical to typing the commands on different lines The ampersand 'D( is another command terminator which causes the command preceding it to run in the "ac!ground %ipes are used to send the output of one command as input to another command
Co44and Grou2in!5 ?+
If the output of the commands date and *ho has to go to a single file, then typing, $ date"who |wc l ! file < nter!
2G Linux
NIIT
will not do the needful $ cat file < nter! 2 *nly the output of *ho 5 *c l has gone to file This is "ecause the precedence of 3 is greater than 1 %arentheses can "e used to overcome this difficulty #onsider the following code2 $ #date"who | wc -l$ ! file < nter! $ cat file < nter! @on #ct A 014074AA C%< 1;;; 2
Exa42le
$ #date"who$ | wc -l E The output of date and *ho are concatenated into a single stream which is then piped through the *c l command The *c l command counts the num"er of lines and prints the result
)yntax
head [options] [file name] tail [options] [file name] The usual use of the head or tail command is to display a certain num"er of lines at the terminal
Exa42le
$ head -% /etc/passwd root4'40404root4/root4/bin/bash bin4'41414bin4/bin4 daemon4'42424daemon4/sbin4 This command displays the first three lines from the "eginning of the file /etc/passwd
Exa42le
$ ls -l | tail -& -r*-r*-r-1 %teve -r*-r*-r-1 %teve %teve %teve EF #ct 1; 2242F y AF #ct 12 0940; y.bak
This command displays the last two files from the output of the ls l command
)yntax
chown [options] owner[.[group]] file/s! chown [options] .group file/s! chown [options] "reference#rfile file/s!
NIIT
Linux 21
-f
-v -c
--dereference -h
--reference(<filename!
)yntax
chgrp [options] group! file/s! chgrp [options] --reference# filename! file/s!
;efer to the following documents+3e" sites for additional information and tips on the vim editor
http://www.gnu.org/so$tware/emacs/emacs.html/ http://www.wcnet.org/j.awodn/emacs/
Ti2
1( To set the options permanently for the vim editor, every user can create the file, .vimrc, in the home directory and set the options in that file 5very time you start the vim editor, the settings will "e read from the rc file 2( For example, you can create a file vimrc *ith the line set nu. Go* *hen you open vi: you *ould get line num"ers on the screen This can "e used in de"ugging #$$ programs .( To go to a specific line num"er, say 2G, use2
22 Linux
NIIT
vi $2G myfile c Aou can also use other editors in Linux li!e emacs, ,oe, or pico
E4a-s editor
The emacs#editor is invo!ed "y the following command from the shell prompt2 emacs [command line switches] [file/s]
Exa42le
(%teveHlocalhost %teve)$ emacs The a"ove command will start the emacs editor and create a new file The following opening screen is displayed2
The following are some of the commonly used commands in the emacs editor2
Command <Ctrl> ) <Ctrl> f <Ctrl> p <Ctrl> n Action Mo%es to pre%ious character Mo%es to next character Mo%es up one line Mo%es down one line
NIIT
Linux 2.
<Ctrl> v <Alt> v <Ctrl> a <Ctrl> e <Ctrl> h <Ctrl> s <Ctrl> x u <Ctrl> x <Ctrl> c <Ctrl> x <Ctrl> s <Ctrl> g
Mo%es to the next screen Mo%es to the pre%ious screen Mo%es to the beginning of the line Mo%es to the end of the line ,nters the emacs online -elp .earches forward for a string /ndoes the last edit ,xits emacs .a%es the file 0ancels the current command *his is used when &ou start to issue a command and then decide not to execute it' (or example) &ou issue the <Ctrl> x command and then emacs waits for &ou to issue the action to be taken' Now if &ou wish to cancel the command) use the <Ctrl> g option to come back to the main section of the document'
Commands in emacs ;efer to the ta"le given "elow for some commands to delete text
Command <Ctrl>d <Ctrl>k Action 1eletes char 1eletes line
Deletion Commands
21 Linux
NIIT
3rite a command to find the num"er of people staying in the state of 4ansas 3rite a command to display the complete details along with the line num"er in which the details
are present for the customer Linda
)olution
a( To find the num"er of people staying in 4ansas, you type the following command2 , grep -c -.ansas- /ustomer "( To display the complete details along with the line num"er for the customer Linda, type2 , grep -n -0inda- /ustomer
%ust a Minute6
The details of various customers who have registered with >ia/ Telecommunications are stored in the "ustomer file )ample data from the file is as follows2 80000018:8=ngela8:8%mith8:81B22E !adiance ourt8:8Iansas ity8:8Iansas8 80000028:8Jarbara8:8Kohnson8:8227 Jeach =ve.8:8=le'andria8:8Lirginia8 800000E8:8Jetty8:8Milliams8:81 <read !oad8:8$ublin8:8Neorgia8 800000A8:8 arol8:8Kones8:87B9 Ourling !d =pt8:8Gorton8:8Iansas8 80000098:8 atherine8:8!oberts8:8990F =Puiline ourt8:8Gorton8:8Iansas8 80000228:8Koyce8:8&hillips8:89E9 $ar*in =venue 8:8 olumbus8:8Neorgia8 800002B8:8Qinda8:8Qe*is8:8192A &atagonia Qane 8:8 olumbus8:8Neorgia8 80000EF8:8!uth8:8Nreen8:8A9; !idge !oad 8:8@iddle <o*n8:8Ge* Kersy8 RRRRRRRRRRRRR RRRRRRRRRRRRR In the file, the field delimiter is E,E The various fields are #ustomer#ode, FirstName, LastName, 0ddress, #ity, and )tate 3rite a command todisplay only the FirstName and the LastName of the customers living in @eorgia
NIIT
Linux 26
)olution
$ grep 8Neorgia8 ustomer 5 cut -d8:8 -f2:E 0lternatively, you can use redirection to accomplish this tas! $ grep 8Neorgia8 ustomer 3 tempfile
%ust a Minute6
Aou need to export the contents of the file "ustomer1-etails.dat#present in the +/"ustomer"alls directory into a data"ase The exported data has to "e in uppercase 3rite a command to view the data in the new format on the screen, one screen-full at a time
)olution
$ cat ~/customer alls/customer-$etails.dat5tr 8(a-z)8 8(=->)8 5 less
0n!uided #ra-ti-e
Con3i!urin! the Resour-e
All the students must connect to the primar% Linux server for the Unguided Practice. You must execute the script /root/sem1/mrweek2/mrweek2 to configure the student logins. You should !e logged in as the root user to execute the script.
B. cat northcolleges southcolleges 33 allcollege 7. cut -d848 -f2:B C ollege 5 tee olldata
a+ grep 8%teve8 messages "( grep -c 8%teve8 messages or grep 8%teve8 messages 5 *c -l
29 Linux
NIIT
;. chmod 000 messages vi messages Aou should get a message permission denied 10. chmod A00 messages vi messages Aou would now "e a"le to view the contents "ut not "e a"le to modify it It would give message read only file when you use the command 2w& to exit In case you still want to save it, you can use 2w&R command to save your changes 11. mkdir impdata chmod 000 impdata cd impdata Aou should get permission denied message 12. chmod u6r* impdata. Now you should "e a"le to change your current directory to this directory "ut you will not "e a"le to create a su"directory 1. The students should use the vi editor to edit the file that is stored in the userEs home directory vi pro,plan a( set nu
"( 8ove the cursor to the line num"er 1. and press dd c( 8ove the cursor to the line num"er D and press -
d( Type 4PU to &uit without saving e+ vi pro,plan f( 8ove the cursor to the first line and press o to insert a "lan! lin! after the current line
g( Type V% followed "y 49 to move to the third line h( 7se the yy command to copy the line num"er E, then move the cursor to the end of file and press p i( ,( 7se the u command to undo the paste option %ress 5)# followed "y /#liver It would search for *liver Now use the ; option to replace it with )teve %ress / again to repeat the last search 0gain press ! to replace it with )teve
!( 8ove the cursor to the fourth line and then move it right till it reaches SThe most S %ress the ' !ey repeatedly to delete the line l( 8ove the cursor to line 6 and use the ; option to replace n with a( ;epeat the same step for line 9 to 11 and replace 2 with "(, . with c( and so on Aou can also delete the character n and insert the series a( "( etc
NIIT
Linux 2D
m( %ress dd on the fifth line and then press p to place the line "elow the sixth line n( 7se the insert mode to add the text in the vi editor o( 7se the 4*P option to save the file
Additional Exer-ises5
:1( The following command would give the re&uired output2 ls -l 5 grep 8W-..'8 5 tr -s 8 8 5 cut -d8 8 -f; X2+ 5xecute the command4 umask 022 Now when you create a file, its permission would "e2 BBB-022 Y BAAY -r*-r--rZ XE+ [se the 4r option to read the contents of the second file to the first file.
Lesson Three
Ex2erien-es
;elate the concepts in this class with the concepts covered in %LT This is the first time the students would "e writing shell scripts 5xplain the concept of how to execute the shell script so that they are a"le to create and execute the shell scripts ;elate the concepts covered in the shell script with the concepts covered in %LT 5xplain the logic of shell script using flowcharts The while, until and for commands are similar in nature 5xplain the similarity "etween these commands
2C Linux
NIIT
Aou can also tell students a"out the file bash1pro$ile, which is a special shell script that is executed automatically when a user logs in This file is used for configuring the environment information for a Linux user Aou may want to open a sample#.bash1pro$ile file to display its contents to students
+A/
:1 3hat is the e&uivalent of a shell script in 3indows+8) >*)= 01 In 8) >*), the "atch files are similar to the shell scripts of Linux The e&uivalent of the shell script, .pro$ile, is the autoexec.bat file 3indows also has "atch files with a .bat extension 0dditionally, 3indows NT files with the extension cmd are used The .cmd files are more powerful than the .bat files :2 #an Linux act as a programming language= 02 The statement TLinux - 0 programming languageU is incorrect Linux is an operating system and not a programming language such as #$$ 0lthough Linux provides a lot of programming constructs, they are typically used to configure the environment and automate tas!s and not for writing applications Note2 3riting shell scripts is commonly referred to as scripting :. #an one shell script execute another= 0. Aes, in fact it is very common to call one shell script from another Aou can see the contents of the file .bash1pro$ile, which first executes the file .bashrc from the home directory of the user :1 3hat are the application areas of shell scripts= 01 )hell scripts are used for various reasons, "oth "y the end user and the system administrator The end user typically writes shell scripts to automate common activities, such as copying files The system administrator uses shell scripts for various administrative tas!s, such as ta!ing a "ac!up Various shell scripts come with the Linux system and can "e used in areas, such as starting and stopping services, and setting the user environment
Additional In2uts
Aou can ma!e the students refer to system shell scripts, such as2
Additional Exer-ises
1 2 0 shell script can "e executed "y the WWWW command '0ns2 sh or bash( The WWWWW environment varia"le stores the path to the userJs home directory '0ns2 \#@V(
NIIT
Linux 2B
3rite a shell script that accepts two num"ers num1 and num2 It should interchange their values and display on screen
echo -n 8Vnter read num1 echo -n 8Vnter read num2 tempY$num1 num1Y$num2 num2Y$temp echo 8Lalue of echo 8Lalue of
%ust a Minute...
3rite a shell script that calculates the num"er of unanswered &ueries at the call center The script should accept the total num"er of &ueries reported in a day and the num"er of &ueries answered to calculate the num"er of unanswered &ueries Total num"er of unanswered &ueries P Total num"er of &ueries - Num"er of answered &ueries
)olution
#reate a file called callpending using the vi editor with the following contents2 echo 8&lease enter the total number of Pueries reported today.8 read totalPueries echo 8&lease enter the number of Pueries ans*ered.8 read ans*ered pendingY$??totalPueries-ans*ered++ echo 8Gumber of calls pending Y $pending8 Type the following command to execute the shell script2 $ bash callpending 0lternatively, you can assign the execute permission to the file and use the following command to execute the shell script2 $ chmod 6' callpending $ ./callpending
%ust a Minute...
.G Linux NIIT
0t the call centers, the performance of a #ustomer #are 5xecutive is measured "y the percentage of &ueries answered for the day 3rite a shell script that displays the grade given to an employee on the "asis of the percentage of calls answered for the day
Percentage of calls answered the same day #34 ! 34 and !64 #64 Grade 5%erage 7ood 8utstanding
)olution
Create a file called grade using the vi editor with the following contents: ]U/bin/bash echo 8Vnter the percentage of calls ans*ered same day.8 read actual if ( $actual -le F0 ) then echo 8^our Nrade elif ( $actual -gt F0 -a then echo 8^our Nrade else echo 8^our Nrade fi
Type the following command to execute the shell script2 $ bash grade
0lternatively, you can assign the execute permission to the file and use the following command to execute the shell script2 $chmod 6' grade $ ./grade
%ust a Minute...
>ia/ Telecommunications offers its customers various services Aou need to create a menu that displays the service names, and when the customer selects a name, its description is displayed The following ta"le displays the various services and their description2
NIIT
Linux .1
Serial Number 1 2 3 = ?
Service Name
Description
9ou :ust need one cell;phone number where%er &ou tra%el across the world' 9ou can record &our message when &ou are unable to take a call' 9ou can recei%e e;mail messages on &our cell;phone' 9ou can displa& the callers telephone number on &our handset screen whene%er &ou recei%e a call so that &ou know who>s calling' 9ou can order for a pi@@a from &our cell;phone'
)olution
3rite the following shell script2 12/)in/)ash echo - 0ist of 3ervices 4ffered )+ 5iaz 6elecommunications echo - 1$ 7lo)al 'oamecho - &$ 8-mailecho - %$ 9ail on 9oveecho - 4$ /aller-:5echo - ;$ 5ial a <izzaecho n -3elect the service for which +ou need more information =1-;> ? read choice case ,choice in 1$ echo -@ou Aust need one cell-phone num)er wherever +ou travel across the world.- "" &$ echo -@ou can record +our messages when +ou are not a)le to take a call.-"" %$ echo -@ou can receive e-mail messages on +our cell-phone.-"" 4$ echo -@ou can displa+ the callers telephone num)er on +our handset screen whenever +ou receive a call so that +ou know whoBs calling.-"" ;$ echo -@ou can order for pizza from +our cell-phone.-"" C$ echo -@ou have selected an invalid option.-"" esac Aou can assign the execute permission to the file and use the following command to execute the shell script2 $ chmod 6' menu $ ./menu
%ust a Minute...
Aou need to store the names, e-mail addresses, and telephone num"ers of eight employees wor!ing at the #ustomer #are #enter The data is to "e stored in the file ccemplo(ee in the following format2 5mployee#ode 2 5mployeeName 2 5-mail 2 Telephone-Num"er The sample data to "e entered is as follows2 1GGG 2 )arah 2 sarah"X&mail com 2 'D.2(2.1-D91. 1GG1 2 %eter 2 peterXspeedmail com 2 '2.1(1.2-2.16 1GG2 2 >avid 2 davidcXspeedmail com 2 '162(16.-2.16 1GG. 2 %aul 2 paulXdia/ com 2 '62.(21.-2.16 1GG1 2 Linda 2 lindalXdia/tel com 2 '161(61.-61D9
.2 Linux
NIIT
1GG6 2 -oseph 2 ,osephmXspeedmail com 2 'C6.(.21-2.16 1GG9 2 Nancy 2 nancyXdia/tel com 2 '.21(.9.-.196 1GGD 2 ;uth 2 ruthpXdia/tel com 2 '91.(D16-.196 1GGC 2 -ane 2 ,anesXspeedmail com 2 'D91(.19-16D1 The employee code for these employees should "e automatically generated and should range from 1GGG to 1GGC The shell script should as! you for the details "ased on the employee code
)olution
To accept the details of the employees and store them in the file, type in the following shell script and store it in a file called acceptdata.sh ]U/bin/bash ecodeY1000 *hile ( $ecode -le 100F ) do echo 8Vnter data for the employee *ith Vmployee ode Y $ecode8 echo -n 8Vmployee Game 4 8 read name echo -n 8Vmail =ddress 4 8 read email echo -n 8<elephone Gumber 4 8 read telno echo 8$ecode 4 $name 4 $email 4 $telno8 33 ccemployee ??ecodeY$ecode61++ done Aou need to execute the shell script2 $ bash acceptdata.sh 0lternatively, you can assign the script the execute permission and execute it as follows2 $ chmod u6' acceptdata.sh $ ./acceptdata.sh
0n!uided #ra-ti-e
Con3i!urin! the Resour-e
&here are no scripts that need to !e executed for the 'ee( ) machine room.
)olutions- 0n!uided
NIIT Linux ..
1.
echo echo echo echo 8\#@V 8&=<\ 8%\QLQ 8Q#NG=@V Y$\#@V8 Y$&=<\8 Y$%\QLQ8 Y$Q#NG=@V8
.1 Linux
NIIT
8.
max(D for##count(1 do echo read if = then fi " count <( 1D " count ( countE1$$ -n - nter num)er ,count ? value ,max -lt ,value > max(,value
9.
echo 8Vnter file name8 read fn echo 8Vnter directory name8 read dn if test -f $.fn/ then if test -d $.dn/ then cp $.fn/ $.dn//$.fn/ echo 8Oile opied 8 else echo 8$irectory does not e'ist8 fi else echo 8Oile does not e'ist8 fi
:.
<31(- nter +our /ommand !-
;.
F(1 echo - nter a Gum)er ? read GH9 while = ,IFJ -le ,IGH9J > do echo ,IFJ sKuare ( Lexpr ,IFJ MC ,IFJL F(Lexpr ,F E 1L done
<.
a( 5xecute the following script named infinitewho2 for##""$$ do echo -5o +ou want to know who is onlineN read answer who done "( %ress Y#trlZ $ [ to stop the process
NIIT
Linux .6
c( 7se the ps command to find the process id of the in$initewho process 7se the kill -O command to !ill the process2 kill -O &14O; d( for??11++ do echo 8$o you *ant to kno* *ho is online_ 8 read ans*er if ( $ans*er Y 8n8 -o $ans*er Y 8G8 ) then break fi *ho done
7.
time find / -name dmesg &! /dev/null
Additional Exer-ises5
Ans *+ #ontents of the main file are2 echo 8@ain @enu8 echo 81+ Oile commands8 echo 82+ $irectory commands8 echo 8E+ Qist the users currently logged in8 read choice case $choice in 1+ ./filecommand11 2+ ./directorycommand11 E+ *ho11 esac #ontents of the file $ilecommand2 echo 8Mhich file command *ould you like help on_8 echo 81+ cp8 echo 82+ mv8 echo 8E+ rm8 echo 8please enter your choice8 read choice case $choice in 1+ man cp11 2+ man mv11 E+ man rm11 esac #ontents of the director(command file2 echo echo echo echo 8Mhich directory command *ould you like help on_8 81+ mkdir8 82+ rmdir8 8E+ls 8
.9 Linux
NIIT
echo 8&lease enter your choice8 read choice case $choice in 1+ man mkdir11 2+ man rmdir11 E+ man ls11 esac Fns &$ aY0 bY1 countY2 echo $a echo $b *hile ( $count -le ; ) do ??cY$a6$b++ echo $c aY$b bY$c ??countY$count61++ done Fns %$ if = ,1 -lt 1 > then echo -@ou have not specified the filename. Hsage? Kuick)ackup <filename!.exit fi if = -f ,1 > then if = -d P/)ackup > then cp ,1 P/)ackup else mkdir P/)ackup cp ,1 P/)ackup fi else echo -6he file +ou have specified does not existfi
NIIT
Linux .D
Ans"er 8
echo 8Vnter the string8 read str echo 8<he number of characters in the string are 48 'Yaecho 8$str8 5 *c -c a echo 8$??' - 1++8
Ans"er 9
echo -n 81 8 for??ctrY11ctrbY1001ctrYctr61++ do ??ctrYctr62++ echo -n 8$ctr 8 ??ctrYctr-1++ echo -n 8$ctr 8 done
Ans"er :
echo 8Vnter string8 read str lenYaecho $str 5 *c -ca *hile test $len -ne 0 do temp-charYaecho $str 5 cut -c$lena
.C Linux
NIIT
Ans"er ;
echo 8Vnter string8 read str lenYaecho $str 5 *c -ca lenYae'pr $len - 1a lYae'pr $len / 2a ctrY1 flagY0 *hile test $ctr -le $l do aYaecho $str 5 cut -c$ctra bYaecho $str 5 cut -c$lena if test $a UY $b then flagY1 break fi ctrYae'pr $ctr 6 1a lenYae'pr $len - 1a done if test $flag -eP 0 then echo 8%tring is palindrome8 else echo 8%tring not a palindrome8 fi
Ans"er <
echo 8Vnter the name of the first file8 read file1 echo 8Vnter the name of the second file8 read file2 cp $file1 ./temp cp $file2 $file1 cp ./temp $file2 rm ./temp echo 8<he files have been interchanged8
Ans"er 7
clear ctrY0 *hile test $ctr -lt 9 do sctrY0 *hile test $sctr -lt $ctr do echo -n $ctr sctrYae'pr $sctr 6 1a done echo ctrYae'pr $ctr 6 1a done
Ans"er >
NIIT
Linux .B
echo 8Vnter a number 8 read num ctrY1 prodY1 *hile ( $ctr -le 10 ) do ??prod Y $ctr " $num++ echo 8$num " $ctr Y $prod8 ??ctrY$ctr61++ done
Ans"er ?
ctrY1 *hile test $ctr -le 20 do totY0 sctrY1 *hile test $sctr -le A do echo -n 8$ctr 8 sctrYae'pr $sctr 6 1a totYae'pr $tot 6 $ctra ctrYae'pr $ctr 6 1a done echo -n 8$tot 8 done
Ans"er 1@
if test $] -eP 0 then echo 8=rguments rePuired 4 [sage 4 cpdel (c5d) parameters8 e'it fi commandY$1 shift if ( $command Y 8c8 ) then if ( $] -ne 2 then echo 8Cnvalid else cp $1 $2 fi elif ( $command Y 8d8 then if ( $] -eP 0 ) then echo 8Cnvalid else rm $" fi else fi echo 8Cnvalid number of arguments 8
1G Linux
NIIT
LINA)
TO
1A 2A 3A =A ?A GA HA 3A 6A
WE' ) ITE)
httpB//www'redhat'comB (or information on latest products and %ersions of Red -at Cinux' httpB//www'redhat'com/support/manuals/B *o download the installation guide) the getting started guide) the reference guide) customi@ation guide) and release notes on Red -at Cinux' httpB//www'google'com/linuxB *o search for an& term on Cinux' httpB//dir'&ahoo'com/0omputersDandD$nternet/.oftware/8peratingD.&stems//N$E/Cinux/B Resources on the $nternet from www'&ahoo'com' httpB//www'europe'redhat'com/documentation/-8+*8/Fash;2rog;$ntro;-8+*8'php3B *o learn more on Fash programming' httpB//www'europe'redhat'com/documentation/-8+*8/5d%;Fash;.cr;-8+*8/index'php3B *o learn more on bash scripting' httpB//www'linuxdoc'org/B *he Cinux 1ocumentation pro:ect' 0ontains lots of 7uides) -8+*8s) (5Is) man pages on Cinux' httpB//www'gnu'orgB *he 7N/>s Not /nix home page' 0ontains lots of interesting articles b& Richard .tallman' www'rpm'orgB Cots of rpms to download and install on the Cinux s&stem'
14A www'linuxworld'comB $nformation on Cinux' 11A httpB//www'linux'comB $nteresting articles on Cinux' 12A httpB//www'linux;india'orgB -ome page of *he Cinux $ndia 8rgani@ation' 13A httpB//freshmeat'netB Cots of source code and programs to download' 1=A httpB//&olinux'comB 1ocumentation on Cinux' 1?A www'isc'tamu'edu/Jlewing/linux/B *he location from where &ou see the *ux' *he logo of Cinux' 1GA httpB//www'woodsoup'org/pro:s/tuxDaKfh/doc/B *he complete histor& of *ux' 1HA httpB//www'gimp'org/B -ome page of using 7$M2 L*he 7N/ $mage Manipulation 2rogramA' *his tool was used to draw *ux'
NIIT
Linux 11
A ==ITIONAL 'OOA)
Iill Iall, Teach Aourself Linux in 21 <ours, pu"lished "y )08) >avid %itts and Iill Iall, *ed#&at#3inux#4nleashed Na"a Iar!a!ati, 3inux#'ecrets, I>@ Ioo!s 3orldwide 0eleen Frisch, 5ssential#'(stem#Administration6#2nd#5dition 8i!e Lou!ides, '(stem#,er$ormance#7uning %atric! 4illelea, 8eb#,er$ormance#7uning:#'peeding#4p#the#8eb
Activity/Problem No.
Cesson 1B 8b:ecti%es 7etting .tarted *he Cinux 8. 1irector& 0ommands in Cinux (ile 0ommands in Cinux .ummar& #otal Cycle" C!" Cesson 2B 8b:ecti%es .tandard (iles Redirection (ilters M5M 2ipes M5M M5M Cocating a (ile in Cinux 5ssigning 2ermissions to (iles ,ditors *he %i ,ditor .ummar&
? 24 1? 34 34 14 11$
? ? 3 1? ? 3 H 14 14 14 ? ? 14
12 Linux
NIIT
#otal Cycle& C!" Cesson 3B 8b:ecti%es 7etting .tarted <ariables Cocal and 7lobal .hell <ariables 0ommand .ubstitution M5M 0onditional ,xecution M5M *he case'''esac 0onstruct M5M *he while) until and for construct *he break and continue statement M5M 0ontrolling *he 2rocess ,xecution .ummar& #otal
1$%
? ? ? 14 3 ? 1? ? H ? 14 ? 14 14 ? 11$
NIIT
Linux 1.