Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Features of Linux Operating System• MultiUser Capability• Multitasking Capability• Communication• Security– Login Security– File Security• Portability- Easily portable
  2. 2. Linux System Organization• Functioning of Linux is manned in three levels– On outer crust reside the application programs andother utilities– At the heart of Linux is the kernel which interactswith the actual hardware in machine language– The streaming of these two modes ofcommunication is done by middle layer . Thismiddle layer can be desktops, window managersand command line shells– The shell or command interpreter as it is called isthe mediator which interprets the commands thatwe give and then conveys them to the kernel whichultimately executes them.
  3. 3. • Three major types of shells are there in Linux• Bourne shell• Korn shell• C shellCurrent versions of linux incorporate all the threeshells enabling you to work in any one of them.When you start the system , you are placed inBourne shell. C shell is used only for the Cprogramming. Its prompt is %. Bourne shell cantackle all the tasks of korn shell but not of C shell.The default prompt of Bourne shell is $ for the userand # for the administrator.As an alternative to a command line interface, Linuxprovides both desktops and window managers.
  4. 4. • When using command line interface, you are given asimple prompt at which you type in your command.The Prompt for the user is $ whereas for theadministrator the prompt is #.• File structure of Linux. The file system of linux starts ata directory called the root (/). Under the root directoryare various other directories as• proc- kernel resides in proc• bin- contains executable files• lib- contains all library functions• usr- All users are in usr directory• etc- Binary executable files required for systemadministration• tmp- temporary files created by linux or users• dev- Device related files
  5. 5. • /proc bin lib dev usr tmp etcuser1 user2 user3(Root)
  6. 6. • Block distribution of DiskIn linux, the hard disk is divided into differentblocks each of the size of a multiple of 512KB.The various blocks are:• Boot block- containing all the files for booting• Super block- contains temporary and emptyfiles. Contains information regarding number offiles that can be included in a file system• Inode block- contains inode numbers. Each filein linux has a unique inode number. Alsocontains file permission entries. For storing allthis information, an inode table is maintained ininode block• Data Block – contains all the user created files
  7. 7. • Creating a file• Two commands are there for creating files• touch• cat• touch <filename>- This command creates empty files. Thearguments can be more than one file at a time• cat- This command is used for two purposes– For displaying the contents of the file– For entering data into the already created fileFor entering datacat > <filename> On entering this command, the cursor will be placed atthe line next to command line. After text entry is finished, press ctrl+d tofinish• Cat command can also be used for concatenating two files.• cat filename1 filename2 > newsample• This would create newsample file which contains contents offilename1 and filename2. if newsample contains the contents,they will be overwritten.
  8. 8. • In order to append to the previous contents“append output redirection operator”, >>, canbe used as• cat file1 file2 >> newfile• Copying a file- the copying of files is done inlinux using cp command• cp source target• If target file does not exist it will be created andif it exists, it will be overwrittencp source target directory• The files will be copied to the directory. Theaddresses mentioned can be complete addressor relative address
  9. 9. • The various options of cp command are:• -i – for invoking cp in interactive mode.• -r – this copies the entire directory structure• Examples• cp -i file1 file2• cp –r directory1 directory2
  10. 10. • Command to remove the files from linux• rm <filename>• Options with rm command are:• -i option- interactive mode. Asks forconfirmation to delete• -r option –this command deletes directories andsubdirectories.• rm –r dir1• -f option- removes files forcibly
  11. 11. • Renaming of the files- the renaming of the files isdone using mv command. This command is also usedfor moving the files from one location to another• mv test sample• mv command also has the power to renamedirectoriesmv olddir newdirProvided newdir is not already existing.A group of files can be moved to a new directory withmv commandmv file1 file2 file3 file4 directoryThe various directories are separated from each otherwith a forward slash (/)
  12. 12. • Directory related commands-• pwd- This command is used to see the presentworking directory$ pwd• Creating directory in linux- The directory can becreated in linux with the command• mkdir <directory name>• Changing the directory- The user can shift from onedirectory to another using cd command. cd commandcan be used with both absolute and relativepathnames. For absolute pathnames, we can start thepath with a forward slash (/).• There is a better way to of navigation available formoving between two directories with same ancestor.
  13. 13. • Linux offers a shortcut---the relative pathname---thatuses either the current or parent directory as referenceand specifies the path relative to it. A relativepathname uses one of these symbols• .(a single dot)---This represents the current directory• ..(two dots)---This represents the parent directory• Examples:• cd .. – Moves the user to the parent of the currentdirectory.• cd ../.. - Moves the user to the parent of the parentof the current directory. Any number of .. Can becombined in a cd command but they should beseparated by a ‘/ ‘ .
  14. 14. • cp /home/kumar/.profile .• This copies the .profile file to the currentdirectory• Every user, when login to a linux system isallotted a home directory by the system. Thispathname is stored in /etc/passwd file.Thispathname can be seen using the echocommandecho $HOMEHOME is the shell variable that knows thehome directory.
  15. 15. • Removing directory- The directories in linux areremoved using the command rmdir• rmdir <directory name>• The directory to be removed must be empty.We can also remove multiple directories in oneshot• rmdir pis/data pis/prog pis• You can’t remove a directory until you areplaced in the directory hierarchically above theone to be removed.
  16. 16. • ls – Listing directory contents• ls command lists all filenames to current directory• ls <filename>--- This command is to check whetherthe filename exits or not• ls options-• ls has a very large number of options.• -x – When you have several files, its better to displaythe filenames in multiple columns.• Identifying the directories and executables (-F). Thisoption lists the files with identification marks for filesand directories. Combining this option with –xproduces a multicolumnar output as well.• ls –Fx• The * indicates that file contains executable code and /refers to the directory.
  17. 17. • -a – Shows the hidden files. These are the filesthat begin with a dot. These files don’t show upnormally but they can be viewed with –a option.• ls –axF• -R– This option lists all the files andsubdirectories in a directory tree• ls –xR• -r – sorts the files in reverse order• -1 – One filename in one line• -d – Lists only dirname if dirname is a directory• -t – Sorts filenames by last modification time.• -i – Displays the inode numbers
  18. 18. • -l – listing file attributes. The –l option displaysseven attributes of a file• Number of blocks occupied by these files inthe disk each of 512 bytes• File type and permissions• Links• Ownership• Group ownership• File size• Last modification time• filename
  19. 19. • ls –l – this option of ls command is used fordisplaying the attributes of the file. –l stands forlong. This option displays seven attributes ofeach file and subdirectory in a particulardirectory. The list is preceded by words total72, which indicates the total number of blocksthese files are accommodating. Each blockconsisting of 1024 bytes. The seven attributesdisplayed by the option are :• File permissions and type- the first columnshows the type and permissions associatedwith each file. The first character in this columnis mostly a ‘–’ which indicates that the file is anordinary file. For directories, this entry isrepresented by a character ‘d’.
  20. 20. • After this first character, there are series ofcharacters in this column that can take thevalue r,w , x or - . These character representthe various types of permissions associatedwith a file. There are three types of permissionsthat a file can have• r – read permission• w – write permission• x – Executable permission• Linux follows a three tiered file protectionsystem that determines a file’s access rights.The permission string is thus broken down intothree groups. Each group here represent the
  21. 21. category and contains three slots, representing theread, write and execute permissions of the file in thatorder. The read permission allows the group to readthe file, w indicates write permission, you can editsuch a file with an editor, x indicates executepermission, the file can be executed as a program.The presence of – indicates the absence ofcorresponding permission. The three groups indicatedin the listing are:• Owner- The one who creates the file is the owner ofthe file• Group- When opening a user account, the systemadministrator assigns the user to some group. Groupscan be seen in the file /etc/group (both group id andgroup name)• Others- Other is the one who is neither the owner ofthe file nor belongs to the group.
  22. 22. • Links – the second column of the ls listingrepresent the number of links associated withthe file. This is actually the number of filenamesmaintained by the system of that file. Linuxallows a file to have many names even thoughthere is a single file on the disk.• Ownership- The third column represent theowner of the file (the one who created the file).The owner has full authority to tamper with thefile’s contents and permissions---a privilege notavailable with others except the root user.Similarly, you can create, modify or removefiles in a directory if you are the owner of thedirectory.
  23. 23. • Group ownership- This column represents thename of the group to which the file belongs• File size- The fifth column represents the sizeof file in bytes i.e amount of data it contains. Itis actually character count of the file and not ameasure of the disk space that it occupies. Thedirectories show smaller file sizes. This is to beexpected as a directory maintains a list offilenames with an identification number (inodenumber) for each file. The size of the directoryfile depends on the size of this list---whateverbe the size of the files themselves.
  24. 24. • Last modification time-the sixth, seventh and eighthcolumns indicate the last modification time of the filewhich is stored to the nearest second. A file is said tobe modified only if its contents have changed in anyway. If we change the permissions or ownership of thefile, the modification time remains unchanged.• Filename- The last column displays the filenamesarranged in ASCII collating sequence.
  25. 25. • ls –d –To force ls to list the attributes of adirectory, rather than its contents, -d option canbe used.• ls –ld <directoryname> <directoryname>• Directories are easily identified from the list bythe first character of the first column, whichhere shows a d.• For device files, this first character is identifiedas either b or c.
  26. 26. • Changing the file permissions- A file ordirectory is created with default set ofpermissions and this default is determined by asimple setting (called the umask). Generally,the default setting write protects the file from allexcept the owner, though all users may haveread access. To see the default permissions ofa file, create a new file and see its permissions.• By default, For any file, the execute permissionis not given to any type of users (owner, groupor others) To do that, the permissions of the fileneed to be changed. This is done with chmod
  27. 27. • The chmod command is used to set thepermissions of one or more files for all threecategories of users. It can be run only by theowner and the super user. The command canbe used in two ways:• In a relative manner by specifying the changesto the current permissions• In an absolute manner by specifying the finalpermissions.
  28. 28. • Relative permissions- When changingpermissions in relative manner, chmodchanges only the permissions specified in thecommand line and leaves the otherpermissions unchanged.chmod category operation permissionfilename• category includes owner, group or otherswhose permissions are to be changed• operation includes assign or remove apermission• permission specifies read, write or executepermission which is to be changed.
  29. 29. • Suitable abbreviations are used for each of thecomponents to frame a compact expression tobe used as an argument to chmod• Abbreviations used:Category Operation permission• u- owner +--Assign permission r- Read• g- group - ---Remove permission w-Write• o- others =--Assign absolute x-Execute• a- all(ugo) permission
  30. 30. • To assign execute permission to the owner, thecommand will be• chmod u+x abcTo enable all catogories to have execute permissions wecan havechmod ugo+x abc; ls –l abcorchmod a+x abcIf we do not specify the category, the permissions areassigned or removed, as the case may be, to all thecategorieschmod +x abcThis will assign execute permissions to all the users forthe file abc
  31. 31. • chmod can accept more than one file name inthe command line• chmod also accepts multiple expressionsdelimited by commas• chmod a-x,go+r abc• More than one permission can also be set inone chmod command• chmod o+wx abc
  32. 32. • Absolute permissions- We can also change thepermissions of a file using a string of three octalnumbers. In this case we are not interested inknowing the previous permissions of the fileand want to set all nine permission bitsexplicitly.• Each type of permission is assigned a numberas shown:• Read permission---4• Write permission----2• Execute permission---1
  33. 33. • For each category we add the numbers thatrepresent the assigned permissions. Forinstance, 6 represents read and writepermissions and 7 represents all permissions.Thus if we want to assign all the permissions toall the category of users, our each octal digitwill be 7 and the command will bechmod 777 abcSimilarly, 000 indicates no permission to any ofthe categories.
  34. 34. • Directory permissions- Directories also have their ownpermissions and significance of these permissions differ fromthose of ordinary files. Read and write permission of anordinary file are also influenced by permissions of directoryhousing them.• Read permission for a directory means that the list of filenamesstored in that directory is accessible. If a directory’s readpermission is removed, ls won’t work.• Write permission of a directory implies that you are permitted tocreate or delete files in the directory. Whether you can modifythe contents of the file in the directory lies with thepermissions of the file not of the directory• Execute permission of a directory implies that you can traverseit till its last subdirectory.• By default any new file that we create has one link whereas anynew directory we create has two links. Because that directoryname appears in two directory files. For example, if dir1 iscreated inside aa1 directory, one entry for the file exists in aa1and one entry exists in dir1 itself as current directory (.) .
  35. 35. • umask: Default file and directory permissions• When you create a file or directory , the permissionsassigned to it depend on the system’s default setting.The linux has the following default setting• rw-rw-rw- (666) for ordinary files• rwxrwxrwx (777) for directories• However these permissions are not visible. This isbecause this default is transformed by subtracting theuser mask from it to remove one or more permissions.To see the current value of umask, we can use• umask022this shows an octal number which has to be subtractedfrom system default to obtain the actual default. Thus666 becomes 644 for ordinary file and 755 fordirectories.
  36. 36. • umask is shell built-in command though it alsoexists as an external command. A user canalso use it to set a new default.umask 000
  37. 37. • Changing File ownership- chown command canbe used to change the owner of a file. Bydefault, the person who creates a file is thedefault owner of a file. This can be changed aschown options owner [:group] file(s)chown sharma :dba deptchanges ownership to sharma and group to dbachanging ownership requires super userpermissions. The status is changed from userto super user using su commandsuPassword: ……….
  38. 38. • Changing group ownership- We can changethe group ownership using chgrp command. Bydefault, a group owner of a file is the one towhich the owner belongs. A user can changethe group owner but only to a group to whichhe(owner) also belongschgrp dba dept• The groups and their ids can be seen in file/etc/grouproot:x:0:usersGroupname GroupPasswordGroup IDusers
  39. 39. • Almost every UNIX system, including Linux, providesa facility known as manual pages. These manualpages contain online documentation for systemcommands, resources, configuration files and so on.• The command used to access manual pages is man.If youre interested in learning about other options ofthe ls command, you can typeman lsand the manual page for ls will be displayed.• Unfortunately, most manual pages are written forthose who already have some idea of what thecommand or resource does. For this reason, manualpages usually contain only the technical details of thecommand, without much explanation. However,manual pages can be an invaluable resource forjogging your memory if you forget the syntax of acommand.
  40. 40. • Wildcards.• A key feature of most Linux shells is the ability to refer to more thanone file by name using special characters. These wildcards let you refer to,say, all file names that contain the character `` n.• The wildcard ``* specifies any character or string of characters in a filename. When you use the character ``* in a file name, the shell replaces itwith all possible substitutions from file names in the directory yourereferencing.• Heres a quick example. Suppose that Larry has the files frog, joe, and stuffin his current directory.• ls• frog joe stff• To specify all files containing the letter ``o in the filename, use thecommand• ls *o*• frog joe• As you can see, each instance of ``* is replaced with all substitutions thatmatch the wildcard from filenames in the current directory. The use of ``* byitself simply matches all filenames, because all characters match thewildcard.
  41. 41. •The process of changing a ``* into a series of filenames is calledwildcard expansion and is done by the shell. This is important: anindividual command, such as ls, never sees the ``* in its list ofparameters. The shell expands the wildcard to include all filenamesthat match. So, the commandls *o*is expanded by the shell tols frog joeOne important note about the ``* wildcard: it does not match filenames that begin with a single period (``.). These files are treated ashidden files--while they are not really hidden, they dont show up onnormal ls listings and arent touched by the use of the ``* wildcard.• We mentioned earlier that each directory contains two special entries:``. refers to the current directory, and ``.. refers to the parentdirectory. However, when you use ls, these two entries dont show up.If you use the -a switch with ls, however, you can display filenamesthat begin with ``.. The listing contains the two special entries, ``.and `` .., as well as two other ``hidden files--.bash_profile and.bashrc. These two files are startup files used by bash when user logsin.
  42. 42. • Note that when you use the ``* wildcard, none of thefilenames beginning with ``. are displayed.This is a safetyfeature: if the ``* wildcard matched filenames beginningwith ``., it would also match the directory names ``. and``... This can be dangerous when using certain commands.• Another wildcard is ``?. The ``? wildcard expands toonly a single character. Thus, ``ls ? displays all one-character filenames. And ``ls termca? would display``termcap but not ``termcap.backup. As you can see,wildcards lets you specify many files at one time.• Examples• ls j?e• joe• ls f??g• frog frig
  43. 43. • Utility Commands-Linux supports various utility commands. Some of thesecommands are:• passwd- This command is used to change the login password.• tty- this is called teletype command. This tells the filename of the terminal• uname- Displays the name of the Operating systemuname –r -----displays the version of Operating systemuname –s----- displays the implementation name of Operating Systemuname –n---- displays the machine name• cal command- This is used to display the calendar of the month and <monthnumber> <year>• date command- This command displays the date with timedate--------Date and month with time is displayeddate +%m-------month number is displayeddate +%h------month name is displayeddate +%d------ Date is displayed• echo- Used to display message• who- used to find the persons logon to the systemwho• Username device name date time of login machine name
  44. 44. who –Hu------- This option prints the column headers and u provides additionalinformation• wc command- This command is used to count lines, words and characters in a file. Itcomes with the option –l, -w and –c which allow the user to count number of lines,words and characters.• who am i- the present settings of the terminal are displayed• ps- In linux, every process that runs is assigned a unique process id . To know whichprocesses are running on your terminal, ps command is used.• ps• Options that can be used with ps are:• -a option is used to see the processes of other users• -u is used for seeing the processes of a particular user• -f option is used to display additional information for the process• -e option is used for seeing various other processes of the system
  45. 45. • Creating links of a file- The links to a file are established usingln commandln filename linknameCreated link does not occupy any new entry on hard disk butpoint to the same file with a new name. Making of links to a fileavoid accidental deletion of the file. If the file with a link isdeleted, the link remains.• More:Paging outputlinux offers more pager that displays one page of the output ata –l | more
  46. 46. • Disk related commands- One of the major concernsfor the system administrator of a linux installation isefficient hard disk management. Since the linux filesystem is installed usually on a hard disk itsupkeeping is of primary importance• Checking free disk space• df command- This command reports used and freememory on disk. The various fields that are displayedare:• File system name• Number of blocks• Used• Available• Used%• Mounted on
  47. 47. • Other options used for the command are:• -i – to display the number of inodes used andfree on the file system .df counts the blocks insizes of 512 bytes irrespective of actual blocksize• - T- to display the type of file system
  48. 48. • Disk usage- The du commanddu reports the disk space used by directories. Itreports in terms of number of blocks occupied.du reports details for the current directory. Thiscan be changed by specifying the directoryname with dudu /devTo view only directories and not thesubdirectories, we can usedu –s /dev
  49. 49. • The ulimit command- This command is used toavoid creation of very large sized files on a filesystem that can damage a file system. It standsfor user limit and contains a value that signifiesthe largest file that can be created by the userulimitThe limit is shown in terms of bytes. If a filegreater than this limit is created, it will becurtailedThe limit can also be reduced by usingulimit 1This reduces the size to 1 block i.e 512 bytes or1024 bytes. This change will be effective onlyfor the current session.
  50. 50. • sort- This command is used to sort the contents of the file.Apart from sorting the contents, it is also used for merging twosorted files into a third file. The sorting is done on the basis offirst character of each line. If first characters are same, secondcharacters are matched and so on• sort file1 file2 file3----Sorts the contents of three files• instead of displaying output on the screen we can store it in afile by saying• sort –o result file1 file2 file3• This will sort the three files and put the contents in file result• To avoid repeated lines in the output• sort –u –o result file1 file2 file3• If files are already sorted and we only have to merge them, use–m option sort –m file1 file2Sometimes we want to combine the contents of a file with theinput from the keyboard and then carry out the sorting
  51. 51. • We can even sort only the input from standard inputby just saying• sort• Sort command is also used for sorting their databasefiles which have its information organised in the formof fields. For this we use sort keys. The syntax for sortcommand is• sort –r +pos1 –pos2• Where pos1 and pos2 are the filed numbers fromwhere to start the sort and till which filed number• If –pos2 is not given, key is assumed to extend till theend of the line.• -r indicates the sorting will be in reverser order• To sort on a numeric field, we use the option -n
  52. 52. • cut- Like sort, cut is also a filter. It cuts or picks up a givennumber of character or fields from the specified file. Say youhave a large database of employee’s information. If from thisyou want to view only a few selected fields, cut is the answer.• cut –f 2,7 filename• this command will display the fields 2 and 7• To cut 2 through 7• cut –f 2-7 filename• cut assumes that fields in the file are separated by tab , ifsome other delimiter is used, we have to use –d”<delimitercharacter>” with cut command as• cut –f 2,7 –d”:” filename• cut command can also be used to specify the number ofcolumns that can be cut from an input• cut –c1-2 filename• This will display only first two columns of each line in display
  53. 53. • Searching command-• grep- grep is an acronym for globally search aregular expression and print it”. The commandsearches the specified input fully for a matchwith the supplied pattern and displays it. Whileforming the patterns to be searched, we canuse wild cards.• grep picture newsfile• This would search the word picture in the filenewsfile and if found the lines containing itwould be displayed on the screen• grep picture newsfile storyfilesearch in multiple files
  54. 54. • For search comprising of more than a singleword, single quotes can be used to enclose thesamegrep ‘the picture taken’ –i –n newsfile storyfileIgnore caseNumber of linesin which patternwas foundSingle quotes forpattern more thanone word
  55. 55. • grep realises that you may not always wish to seewhat you search. Rather you want to see the lines notcontaining a particular pattern. This can be done with–v optiongrep –v a* filenamethis will display all the lines that do not contain a wordthat start from a. Also, the lines that contain acharacter ‘a’ are also matched as ‘*’ also denote zerocharactersRegular expressions wild characters used are.-------matches on single character*------matches repeated characters$----- match on the end of line[]---------matches on a class of characters^----- match on the beginning of line
  56. 56. • Examples• ^consists---- matches for all lines that beginwith consists• such$-------matches lines that end with such• B.d -----will match all the lines that contain onecharacter between B and d
  57. 57. • grep options• option Meaning• -c returns only number of matches• -i Ignores the case while searching• -l returns only filenamescontaining a match• -n returns line number of the matchedtext as well as the text itself• -s Suppresses error messages• -v Return the lines that do notcontain the match
  58. 58. • Viewing files- There are two commands usedfor viewing the particular portions of a file.These are head and tail commands• head command is used to display particularnumber of lines of a file.head -15 myfiledisplays the 15 lines of the file from thebeginningtail -15 myfiledisplays the last fifteen lines of a file.
  59. 59. • I/O Redirection and Piping- In all operatingsystems, there is a standard input device and astandard output device. Sometimes it is usefulto redirect the input or output to a file or aprinter. The symbol > implies redirection ofoutput and the symbol < implies redirection ofinput. The symbol > sends the output of acommand to a file or device such as printer.The symbol < takes input needed for acommand from a file rather than from thekeyboard. The symbol >> adds output from thecommand to the end of file without deleting theinformation already in the file.
  60. 60. example cat file1 >file2This command tries to display the output of file1on screen but the output is redirected to the filefile2Similarly, we can use a file as input alsocat < filenamethis will display the contents of the fileWe can also use both input and outputredirecting operators in a single commandcat <file1 > file2This command takes file1 as an input and putthe contents in the file file2
  61. 61. • Piping- This command is used to connect onecommand to another. It can be really useful toredirect the output of one program so that itbecomes the input of another program.cmd1 | cmd2The output of one command becomes the inputfor another command.• Filters- Filters are the commands that takeinput from standard input and display output onstandard output.
  62. 62. • tee command- Linux has a command to send theoutput to the command to a file as well as to thedisplay.who|tee logfile|sorttee command sends the output of who to the logfile aswell as to the sort command• tee command can also be used to send output to afile and to the screen. This is done using thecommandwho| tee file1 /dev/pts/12It is also possible to send the errors to a filecat file2 > newfile 2> errorfile
  63. 63. • Exercises• Count the number of directories and files in thecurrent directory• Sort the names of the users who are currentlylogged and store the names in a file• Store the calendar of current year in the file anddisplay the file• Output of who should be displayed on thescreen with the value of total number of userswho have logged on displayed in the last• Output of ls should be displayed on the screenand from this output the lines containing theword ‘poem’ should be counted and countshould be stored in a file file1
  64. 64. • List all the files beginning with the character ‘P’on screen and also store them in a file calledfile1• All files present in the directory dir1 should bedeleted. Any error, if it occurs while carrying outthis operation should be stored in a file errorlog
  65. 65. • ls –l |cut –c 1|grep d| wc –l -----Number ofdirectories can be seen• who | sort | cut –c 1-7 >file5• cal 2009 | tee file1• who|tee file1|wc –l >>file1; cat file1• ls | tee file2 /dev/pts/12| grep file1 | wc –l >file10
  66. 66. • The Vi editor- vim and gvim• The vim editor included with most of the linuxdistributions is an enhanced version of the vi editor ofunix. It includes all the features of vi editor.• Vim and emac use a keyboard for two differentoperations; to specify editing commands and toreceive character input Used for editing commands,certain keys perform deletions, some execute changesand others perform cursor movement.• Usually these two functions are divided amongdifferent keys on the keyboard• Alphabetic keys are reserved for character input• Function keys and control keys specify editingcommands such as deleting text or moving the cursor.
  67. 67. • The vi or vim editor operates in three modes– Command mode– Input or append mode– Execution or ex mode• In command mode , all the keys on the keyboardbecome editing commands; in the input mode keys onthe keyboard become input characters.• Some of the editing commands such as a or i enterthe input mode. On pressing i key, you leave thecommand mode and enter the input mode. PressingESC key returns the user to the command mode.• With vim, you can use ctrl+O command to jumpquickly to the command mode and enter a command.• Although the vi command mode handles most editingoperations, it cannot perform some, such a file savingand global substitutions. For such operations, youneed to enter the line editing mode which can be doneby pressing a colon. This is the ex mode
  68. 68. • vim <filename>• After executing the vim command, you enter Vi’scommand mode. Each key becomes a vi editingcommand , and the screen becomes a window into thetext file. Text is displayed screen by screen• After entering the text, you can leave the input modeand return to command mode. For saving the file,• Press :ZZ and enter--- will save the file and exit• To save file while editing, press :w and press enter• To quit the editing session, you can use :q. it does notperform any saving. However if you have done somechanges to the file before exiting, you will not beallowed to exit. To override this use, :q!• To obtain online help, enter :help•
  69. 69. • gvim- This is another editor provided which hasadditional menu buttons on the top which canbe activated by mouse clicks. Other facilitieslike cut, copy, paste etc are also provided.
  70. 70. h Left one characterl Right one characterk Up one linej Down one linew Forward one wordW Forward one space- delimited wordb Back one wordB Back one space- delimited worde End of the next wordE End of next space- delimited word0 Beginning of line$ End of the lineEnter Beginning of the next line- Beginning of the previous line( Beginning of sentence) End of sentence{ Beginning of para} End of paraCtrl+F Moves forward by a screen of textCtrl+B Moves Back by a screen of text
  71. 71. • Commands for positioning the cursor in windowh Moves the cursor one character tothe leftBackspace Moves the cursor one character tothe leftl Moves the cursor one character tothe rightspacebar Moves the cursor one character tothe right0 Moves the cursor to the beginning ofthe current line$ Moves the cursor to the end of thecurrent line
  72. 72. • Positioning by linej Moves the cursor down by one linein the same columnk Moves the cursor up by one line inthe same column+ Moves the cursor down to thebeginning of the next line- Moves the cursor upto the beginningof the previous lineenter Moves the cursor down to thebeginning of the next line
  73. 73. • Positioning by wordw Moves the cursor to the right, to thefirst character of the next word.b Moves the cursor back to the thefirst character of the previous word.e Moves the cursor to the end of thecurrent word
  74. 74. • Positioning in the windowH Moves the cursor to the first line on thescreen, or homeM Moves the cursor to the middle line onscreenL Moves the cursor to the last line onscreen
  75. 75. • Positioning in a fileCtrl+f Scrolls the screen forward a full window,revealing the window of text below thecurrent windowCtrl+b Scrolls the back a full window, revealingthe window of text above the currentwindow
  76. 76. • Commands for inserting texta Enter text input mode and appends the text after thecursori Enter text input mode and inserts text text at the cursorA Enters text input mode and appends text at the end ofcurrent lineo Enter text input mode by opening a new line immediatelybelow the current lineR Enters the text input mode and overwrites from thecurrent cursor position onwardsO Enter text input mode by opening a new line immediatelyabove the current lineI Enters the text input mode and inserts text at thebeginning of current line
  77. 77. • Commands for deleting text (work in command mode)x Deletes the character at the current cursor positionX Deletes the character to the left of the current cursorpositiondw Deletes the word from the cursor to the next space or tothe next punctuationdd Deletes the current linenx, ndw, ndd Deletes n characters, n words or n linesd0 Deletes the current line from the cursor to the beginningof the lined$ Deletes the current line from cursor to the end of the line
  78. 78. • Miscellaneous Commands. Repeats the action performed by the last commandu Undoes the effect of last commandU Restores all changes to the current line since youmoved the cursor to this lineJ Joins the line immediately below the current linewith thecurrent line~ Changes the character at the current cursor positionfrom upper to lower case and vice versa:sh Temporarily returns to the shell to perform some shellcommands. Type exit to return to viCtrl + l Clears and redraws the current window
  79. 79. • Commands for quitting viZZ Write the buffer to the file and quits vi:wq Write the buffer to the file and quits vi:w filenameand :qWrite the buffer to the file filename and quits vi:w! filenameand :qOverwrites the existing file filename with the contents ofthe buffer and quits vi:q! Quits vi whether or not changes made to the buffer werewritten to a file:q Quits vi if changes made to the buffer were written to afile
  80. 80. • Block commands- these are the commands that applyto a block of text. For all the block commands,following things hold:• All the block commands work in ex command mode• Line numbers should be associated with the textbefore we issue any block commands. This is sobecause block commands need to be told the linenumbers on which they are supposed to operate.Inorder to make the line numbers displayed alongwith the lines, we have to set number in ex mode:set numberUse of : makes it a line editing command which isissued at the bottom of the screen. The lines of the fileare numbered from 1 onwards
  81. 81. • Various block commands are:nd Deletes nth line:m,n d Deletes m to n lines where m and n are line numbers:n mo p Moves line n after line p:m,n mo p Moves lines m to n after line p:m co p Copies line m after line p:m,n co p Copies lines m to n after line p:m,n w filename Writes lines m to n to a file:m,n w >>filenameAppends lines m to n to a file: r filename Reads the contents of the file filename at current cursorposition:r !comamnd Executes the shell command and output of the command isread at the current cursor position
  82. 82. Command Function/pattern Searches forward in the buffer for the nextoccurrence of the pattern of text. Positionsthe character under the first character of thepattern?pattern Searches backwards in the buffer for the firstoccurrence of the patterns of text.n Repeats the last search commandN Repeats the search command in theopposite direction
  83. 83. • While searching a pattern you may want tosearch all occurrences of the word irrespectiveof its case. In such a case, we can set toignore the case• :set ignorecase or :set ic• Find and replace- We can also replace thefound pattern with a new one in vi editor
  84. 84. Command Function:s/str1/str2 Replaces the first occurrence of str1 withstr2 in current line:s/str1/str2/gReplaces all occurrences of str1 with str2 incurrent line:m,ns/str1/str2/gReplaces all occurrences of str1 with str2from lines m to n:1,$s/str1/str2/gReplaces all occurrences of str1 with str2from lines 1 to last:1,.s/str1/str2/gReplaces all occurrences of str1 with str2from first line to current:.,$s/str1/str2/gReplaces all occurrences of str1 with str2from current to last
  85. 85. Command Function:set nu Set display of line numbers on:set nonum Set display of line numbers off:set eb Beep the speaker when an error occurs:set noeb Do not beep the speaker:set ai Set autoindent on: set noai Set auto indent off: set ic Set ignorecase on: set noic No ignore caseTo get a list of all set options use:set all
  86. 86. • Multiple file editing in vi• Vi permits editing of multiple files at one go.• vi filename1 filename2 filename3….• The first file given as argument is opened forediting• At any moment , to find out the number of filesloaded for editing• : args• This displays the list of files with the name ofthe file being currently edited enclosed withinthe square brackets []
  87. 87. • After editing the current file, we can shift to nextfile by typing:• :n• The shift to next file is only allowed if thecurrent file is not edited . If the current file isedited, we have to use• :n!• Unlike n, there is no command available forediting the previous file. However we can go tothe first file for editing using’• :rew• or :rew!
  88. 88. • If a new file is to be opened for editing instantly• :e filename• This filename will not be added to the previouslist of filenames.• :f• Displays the name of the current file
  89. 89. • Command line options in viCommand Functionvi +100 file Loads file and places cursor on the 100thline in the filevi +/pattern file Loads file and places cursor on the firstoccurrence of the matching patternview file Displays file in the read only mode of vi.Any changes made to the buffer will notbe allowed to be written to the file
  90. 90. • Shell Script- A shell script or a shell program is aseries of commands given to the interpreter at onetime. Instead of specifying one job at a time, we givethe shell a to-do list –a program that carries out anentire procedure. Such programs are known as shellscripts.• The script can be written using any of the editors oflinux. The script files are not executable and has to bemade executable using chmod command.• When we execute a command at the dollar prompt,they are executed in the shell that was invoked whenwe logged in. As against this, when we execute a shellscript, the login shell creates a new shell,a newcommand interpreter and waits idly in the backgroundwhile the new shell executes our shell script.
  91. 91. • Inorder to run a shell script,• Type the script in vi editor• After saving the text,• sh <filename>• Inorder to run the file with its name only, wehave to change the permissions of file to getexecutable permission. This is done using• chmod u+x filename• After getting executing permissions, we can runit as• ./filename
  92. 92. • Interactive shell script- Two basic words in shellvocabulary read and echo are used for makinginteractive shell scripts.• echo is to display a message• read is used for taking input from the user