You are on page 1of 35
The last line mode is one in which the user is able to enter special commands which typically start with the ‘:’ (colon) When ‘vi’ is invoked, it comes up in ‘command’ mode. For the user to be able to enter any text, the user must type a command that takes him into ‘input’ mode. The user can come back to the ‘command’ mode by pressing the ‘Escape’ key ‘The ‘vi’ editor can be invoked by typing the following command at the prompt ia Once ‘vi’ is invoked, the following screen is displayed. Remember that the name of the file to be ge (“Empty Buffer”) is displayed at opened has not been specified. That is the reason that a mes the end of the screen. [kevin@icarus kevin] $ vi file1 VIM - Vi IMproved Sto ESN CEU Cea Pain Figure 1: ‘vi’ invoked without a filename An existing file can also be opened by giving its name. The cursor is brought to a specific line by specifying the line number at the command prompt along with the file name r to the fifth line of the file called The above command positions the curs ‘vi’ also provides the user with the ability to open the file and get the cursor to be at a particular string in the file. The above command takes the user to the line in the file called ‘filel’ which contains the first ‘occurrence of the string ‘hello’ . If the power fails, does ‘vi’ help recover the document ? If yes, what is the option? Also specify how this would work? 3__Inserting Text Assuming that ‘vi’ editor is in command mode, the user will not be able to enter any data. The user will have to switch to input mode to be able to add any data. This can be done by pressing the character ‘i’. The user can now start entering the data. Error that occur while entering the data can be removed by using the ‘backspace’ key. Table | gives a list of the commands which can be used to insert data in the document. Command Purpose i - ike taneet mip ane snkclis Gefire Charme 1 Same as ‘i’ but insertion is at beginning of line ° Opens blank line befove the canfentline = ° Same as ‘o’ but puts blank line after current line a Same as ‘i’ but appends after cursor A Same as ‘a’ but appends at end of line Table 1: List of insertion commands The ‘J’ command joins the next line with the current line. (The Dos and Windows concept of joining two lines by pressing the ‘Del’ key at the end of a sentence does not work here.) 33.4 Navigation The ‘vi’ editor gives the option of navigating without relying on the cursor keys. There are other commands to help in scrolling the screen, The character ‘n’ before the command signifies that the command is repeated ‘n’ number of times Table 2 gives a list of the commands which are used in cursor control. Command Purpose k Same as the “up” arrow key h Same as the arrow key 1 Same as the “right” arrow key j Same as the “down” arrow key w Moves forward by a word ‘nw Moves forward by ‘n’ number of words e Moves to the last character of this word or that of the next ‘ne Moves to the last character of n" next word b Takes the user back by a word ‘n’b Takes the user back by ‘n’ number of words O(zero) or *” _ | Takes the user to the beginning of the line $ Takes the user to the end of the line WG Takes the user to the ‘n’th line [L Takes the user to the last line Table 2: List of cursor navigation commands Command Purpose Cult Scrolls a screen forward Cur-b Serolls a screen backward Ctr-u Scrolls half a_screen backward Curl-d Scrolls half a_screen forward Curl-L Refreshes the screen Table 3: List of screen scrolling commands. 3. Deleting Text Now that we are familiar with entering text, moving around and scrolling, the mechanisms of deletion of text can be dealt with. The ‘Del’ key is be used to delete characters in ‘vi’. The ‘vi? editor provides many other commands which help us delete characters, words and lines. Table 4 gives the list of commands which help in deletion of characters,words and lines. Command Purpose x Deletes one character at the cursor postion “Wx Deletes the next ‘n’ characters at the cursor postion dw Deletes one word at the cursor postion ‘n'dw Deletes “n’ words at the cursor postion d0(zero) Deletes from the cursor postion till the beginning of the line d§ or D Deletes from the cursor postion till the end of the Tine dd Deletes one line at the cursor postion Command Purpose | ‘n'dd Deletes the next ‘n’ lines from the cursor postion | Table 4: List of text deletion commands. ‘command should be used to delete 5 lines of text. 33.6 Undoing Your Changes ‘vi’ has the option of undoing the last action. The ‘uw’ command removes the effect of the last command. For example, if a block of text has been deleted by mistake, it can be undone by using the ‘u’ command. 3.3.7__Replacing Existing Text Now that we have learnt how to add and delete text, let us learn how to replace and overwrite the existing text. = 8 it Replace a single character at the current cursor position. R Invoke insert mode and go on replacing till is pressed | s | Deletes the current character and inserts characters until is pressed | Ss Removes all the characters on the current line and allows the user to enter data Table 5: List of text replacement commands. 3.3.8 __Commands for Saving and Exiting We have learnt how. to perform the basic text manipulations in ‘vi’, let us now see how to save the data. We will now look into the commands for saving files as well as exiting ‘vi’. Almost all the commands discussed earlier are executed from the last line, that is to say that we will be using the last line commands for this. The last line commands start with the colon ( *:’ ). ‘The table given below shows the list of commands to save and come out of ‘vi’. The user must switch to the command mode by pressing the ‘Esc’ key. Command Purpose “q Quit vi : leq! Quit vi without saving changes | Sw Save and continue working in vi - wa Save the changes and exit from vi x Save and exit from vi [zz Save the changes and exit from vi Table 6: List of file save and file exit commands Among the above commands the only command that need not be prefixed with the colon (‘:’ ) is the ‘ZZ’ command. And lo, the land beyond the mountain was so Pree Ue LLL Robert did not have to think twice about hanging up his travelling boots First he carved out his territory by clearing the woods and planting corn, the Figure 2: File saved with the ‘:wq’ command ‘The Figure 5 shows how the file is saved using the ‘:wq’ command. 3.3.9 Copying and Moving Blocks of Text To be able to select a block of text, we need to select the lines of text by taking the cursor to the first line of the text block that we have to copy. We then need to first of all specify the number of lines followed by the command ‘yy’. This copies the specified lines to a tempory buffer. To be able to copy a block of text, we move a copy of the specified text to the temporary buffer. To be able to move a block of text, we move the specified text itself to tempory buffer. The paste command ‘p’ moves the text stored in the temporary storage to the current cursor location, Command Purpose yy Copy a line into tempory storage “n'yy | Copy ‘n’ number of lines into tempory storage ad Move a line into tempory storage ‘n'dd | Move ‘n’ lines into tempory storage P Move the text from tempory storage to the current position of the cursor Table 7: List of move and copy commands In table 7, we find that the line delete command ‘dd’ is used to move the text. This is so because the deleted line goes into a temporary storage from where it can be later moved to a specified location by using the ‘p’ or the ‘P” command. 3. Starting ‘pico’ The user can create a new file or modify an existing file using ‘pico’. For this, the user should type ‘pico filename’ at the command line prompt where ‘filename’ is the name of the file the user wants to edit. Let us say we want to modify a file called Lines. This is done by typing: vin@ ea eae! (if there is no file called ‘Lines’, ‘pico’ will open a new file.) As a result of the command entered the whole screen clears up and we see a display as shown in Figure 13. Lee a COCO CeCe oes erent aU See aes SUSE a aes SUSE a is line 7 feccm Pena t Help *O WriteOut “R Read F eb coe «eae Vo a OOD at it Muss AW Where is *V Next Pg *U UnCut Text *T To Spell Figure 10: The ‘pico’ screen The bottom part is the user menu. A blinking cursor is seen at the top left corner of the page. That indicates current position of the cursor. = Working with ‘pice The most important operation involves moving the cursor. The user can navigate through the file by using the arrow keys. The user can traverse to any point in the file by using the arrow keys. a) Adding Text To add text, take the cursor to the point and input the text. If a spelling mistake is made, the backspace key can be used to delete the character just before the cursor. b) Deleting Lines Let us assume that there are certain lines in the document to be deleted. To delete these, we need to take the cursor to the beginning of the line and press *K’(A key combination of Ctrl+K). This will delete the lines all together. ©) Undoing Changes Ifa line has been deleted by mistake, the deletion can be undone by pressing ‘*U’. It will *undo’ the deletion.(‘Undo’ is performed for the last action not just deletion.) 4) Copying Lines If a line is to be copied we need to perform the following steps: > The cursor needs to be placed at the beginning of the line that has to be repeated. > The key combination Ctrl + K or ‘AK’ is used to cut that line. This incidentally deletes that line > Hence the user will have to use the key combination ‘AU" to retrieve it > Now place the cursor where the line is to be repeated and use the key combination ‘AU? to place a copy of it. ‘The line is now copied. e) Searching for a Pattern Looking for a pattern in a small file is easy. But, if the file is file is long it is difficult to look for such patterns. In such cases, ‘pico’ has a method to look for a pattern or string. To invoke pattern searching, the key combination “AW” has to be used. The ‘pico’ editor will then prompt for the string to search for. The string to be searched for has to be keyed in and the ‘enter’ key to be pressed. The cursor will automatically move to the word searched for. ‘The prompt which appears at the bottom of the screen is as shown in Figure 14. Te kina cerns Reto to) a MLL aLL “C Can Figure 11: Searching for a string 3.4.3 Inserting Text from Other Files The ‘pico’ editor can be used to insert the contents of another into the file being used. To insert the contents of the ‘another’ file into the file ‘Lines’ the ‘AR’ option is to be used. The prompt, which appears at the bottom of the screen, is as shown in Figure 15. inte neon ena YOR Oy Figure 12: Inserting text from a file After all these changes have done, the file will have to be saved. To save a fil “AX? option is to be used. ‘pico’ will ask for confirmation whether you want to save the changes. If the “no” option is selected, then the changes will not be saved. The prompt, which appears at the bottom of the screen, is as shown in Figure 16. Save modified buffer (ANSWERING "No" WILL DESTROY CHANGE: bee: “C Cancel N_ No Figure 13: Prompting to save changes If the user presses *Y" to save the changes, ‘pico’ then prompts the user for a filename. ROR Cee Lo t Help *T To File ‘AB Complete Figure 14: Saving to a file Introduction “In this session, the student is introduced to the standard files and devices in Linux. The use of wild card characters is also discussed here. The concept of filters is introduced and some of the - simpler filters are examined. 52 Standard Files ; __ Inthe Linux operating system, every physical device used by the system is represented by a file, ~The most fundamental of all devices are the keyboard and the monitor. The monitor, which is called the standard output device has a file which is known as the ‘standard output file’ associated in it, Similarly, the keyboard, called the standard input device also has a file, the ‘standard ‘input file’. This means that any command when executed will, by default, try to take the input _ from the keyboard and send its output to the monitor, which is the default output device. Standard Command Standard: Input or | _______yJ {+> Output or files files Standard Error or files Figure 1: Standard Files If, in any case the execution of a command results in an error, the error message is directed to the standard error device, which in most cases is the standard output device namely the monitor. The three standard files also have short forms and file descriptors fe File __| Short Name | Standard Input file | _stdin andard Output file | _stdout [st ndardErrorfile | _ stderr | Table 1: The § standard files ‘These standard files are opened for every user when he logs in. Normally, the ‘cat’ command reads data from all of the files specified by the command line, and sends the same data directly to ‘stdout ecu ort) keane this is file 1 [kevin@ kevin] $ Figure 2: Using the ‘cat? command If the file * exists, then the contents of the file would be sent to the standard output However, if the file name is not specified then ‘cat’ reads data from ‘stdin’ and sends it back to ‘stdout’. Each line that you type is immediately echoed back by ‘cat’. When reading from standard input, you indicate that the input from the keyboard is “finished” pressing the ‘ctrl-d’ key combination [kevin@i erie ened Peer PrN rus kevin] $ cat $3 Devices In Linux, devices, peripherals (discs, printers, floppy drives) are all considered to be files, and are treated as such. The kernel converts the reference to that file into hardware commands to deal with it. The following figure displays a few files from the ‘/dev’ directory Tories w- 1 root sys 14, May 6 1998 Secs etry Pri! root 4, PEP ae uucp Cea Pre es Pra NSS) rr) brw-rw-rw- 1 root floppy May 6 1998 fd0D360 Tea core Nem Cos) ry aa ae ol pbs LEDs Oren eam E Omen Crees reat , EH Tay] ee Ta . PRE ks aed MAUD) PET Pe) Figure 4: Listing of the ‘/dev’ directory We will notice two things about the files in the ‘/dev’ directory Instead of a byte count for how much space a file is occupying we have a pair of numbers, Instead of a ‘d’ or a “-" in the permissions field we have a ‘c’ or a ‘b’. This indicates that they are special files One special file the user should know about is ‘/dev/null’. Anything written to it is discarded. This file is regarded as the trashcan of Linux Quite often when we don’t want the output of a program to appear on the screen or are not really interested in the output, we can redirect it to ‘/dev/null’ ee ue ting of the ‘/dev’ directory Figure 5: Lis As we can see this command does nothing. This is because the contents of buffer get written to Mev/null’. The “>’ (output redirection) used here is a redirection operator which we will be leaming shortly. 54 Wildcards A key feature of most Linux shells is the ability to refer to more than one file by name using special characters, called wildcards. The wildcard **’ specifies any character or string of characters in a file name. When we use the character ‘*” in a file name, the shell replaces it with all possible substitutions from file names in the directory we are referencing. [kevin@icarus kevin] $ Is fil RES eae ence omen ony [kevin@icarus kevin] $ Figure 6: Using the wild character “*° The command given in Figure 6 provides a listing of all files which start with the three characters “Gi. On execution of the command ‘Is file*” the shell expands, the °** and tries to look for files that fits the specified pattern ‘The other wildcard character is the *?’. The ‘?” wildcard expands to only a single character [kevin@icarus kevin] $ !s file? Pio Moa [Ueno acu) i Figure 7: Using the wild character *?” In Figure 7."the user is trying to get the listing of all files which start with the four characters «file'and the fifth can be any character. On execution of the command ‘Is file?", the shell expands the ‘2" and tfies to look for files that fit the specified pattern One important note about the ‘*” wildcard it does not match file names that begin with a single period (+). These files are treated as hidden files. While these files are not really hidden, they don't show up on ‘Is’ command’ listings even if the “*” wild card character is used. 55 Filters: An Introduction A filter is a program that reads data from the output of another program or the standard input, processes it in some way, and sends the processed data to standard output or to another program stdin Or stdout or as output of Filter |g) input for another Command another command command A Filter Figure Let us look at some of the many filters available in Linux: The ‘we’ “ommand * Syntax: we [options] [filename] swe? stands for ‘word count’, The ‘we’ command counts the ‘lines’, ‘words’ and ‘characters’ in a specified file. If the filename is not specified, then input is taken from the keyboard is taken. Tere OL ea ene 74 623 3627Lin1 [kevin@icarus kevin] $ Figure 9: Using the ‘we’ filter The output in Figure 9 shows that the file ‘Lin1’ has 74 lines, 623 words and 3627 characters. Option Purpose -c Prints only the character count -w Prints only the word count [1 | Prints only the line count Table 2: The options of the ‘we’ command 5.5.2__ The ‘sort’ Command Syntax: sort [options] [filename] The ‘sort’ command arranges the output alphabetically. So if we have a file called ‘names’ with the following names: Kevin Jason Chiang Dmitreev Then running the ‘sort’ command will give the output like this. [kevin@icarus kevin] $ sort names Cenrnrg [kevin@icarus kevin] $= Figure 10: Using the ‘sort? filter ‘sort’ is very powerful command having many options. Some of these are listed below: Option : "Purpose b Ignores the leading blanks f _| Folds the characters into upper case i [au Does a numeric sort 2 + Reverses the sort E [-0 _ | Writes the sorted output to a file a *t Specifies the field separator | +nn___| Specifies the order in which the data is to be ordered Table 3: The options of the sort command LHow can we perform a column wise sort ? Syntax: tail [no of lines] [filename] ‘The ‘tail’ command prints the last ‘n'lines of a specified file. The number of lines to be displayed can be specified For example: Tec hkcieomi See XE filter The ‘head’ command is similar to the ‘tail’ command. It however, prints the first ‘n’ lines of the file Figure 1 Jsing the “t 5.5.4 The ‘finger’ Command Syntax: finger [options] [user] Earlier we had said ‘Linux’ is a multi-user system, That means more than one person can be logged in at any given time. To find out information about the users, we use the ‘finger’ command. [kevin@icarus kevin] § finger eet Tty Idle Pts aS CCS Aven Buck Steve Buc Fy May CTO Ge 578-1006 Guest Guest Account MEN bs Soe Pye ud rene cart AVE ont Peete Ld [kevin@icarus kevin] $ (ire Office Phone Room 181 578-1006 Figure 12: Using the ‘finger’ filter The ‘finger’ command provides a lot of information about the users. As it is a potential security Joophole, many system administrators disable the ‘finger’ command. §. The ‘find’ Command Syntax find [path] [expression] ‘The ‘find’ command can search for files or directories that match a given pattern. The same search can be performed for a given directory hierarchy. Figure 13: Using the ‘find’ filter This ‘find’ command looks for any file containing “Lin3? anywhere in its name located under the root (/) directory or any of its subdirectories and prints the output on to the screen. aE e Option ©) a The ‘dit * Command Syntax: diff [first filename] [second filename] The ‘diff’ command is used to find the di follows: rence between two files. Its syntax and output is as (kevin@icarus kevin] § diff Test Exam ro) eRe Ue ee TT emote ky Figure 14: Using the ‘diff’ filter This command actually displays the lines, which are different. ‘The ‘comm’ Command Syntax: comm [first filename] [second filename] The ‘comm’ command is a file comparision program which expects two filenames as its input. It processes the files received as input and displays a three column output on the standard output. The first column gives the lines that occur only in the first file, the second column gives the lines that occur only in the second file and the third column gives all the lines that are common to both the files. us kevin] $ comm file! file2 PUERCO OL Pea RRM Loe TSMR UCR N MR Uo Sa [kevin@icarus kevin] $ emt Figure 15: The ‘comm’ filter nd 8 The ‘tr’ Com § Syntax: tr [options] [characters to be looked for] [characters to be translated into] ‘The ‘tr’ command is used to translate or remove consecutive repeating characters from the characters in the input received by it. In the following case, we see that ‘tr’ is used to convert the input to upper case. @icarus kevin] $ tr z Maer cents THIS LINE IS A SAMPLE LINE OF TE? [kevin@icarus kevin] $ Figure 16: The ‘tr’? command doing a translation In Figure 16, the user gives ‘tr’ two parameters, the first parameter being the characters to be acted upon and the second one being the characters to be translated into. The above example accepts input from the keyboard and converts this into uppercase characters. [kevin@icarus kevin] $ tr—s “ cre Fn ea this _ isa very good place for a picnic [kevin@icarus kevin] $ Figure 17: The ‘tr? command squeezing characters In Figure 17, the ‘tr’ command uses the *-s’ option. The option “-s’ enables the ‘tr’ command to remove the repeating characters that occur in the input string. Here the repeating occurrences of the (**) or space are removed as we can in Figure 17 ut’ Command Syntax: cut [options] [filename] The ‘cut’ command is a filter that is used to vertically cut across columns to extract entire columns (fields) or specific number of characters. [kevin@icarus kevin] $ Ope eek Cerne Peed Figure 18: The ‘data’ file We observe that the data file called ‘data’ contains the name, age and employee id of employees. Each of the fields is separated by a ‘ ’ (space) that is to say, space is the delimiter {kevin@icarus kevin] $ cut -d” “-f1,3 Charles 3243 ou Pe [tran Peavy Figure 19: Using the ‘cut’ command with the ‘-f? option In Figure 19, we find that the delimiter ‘ ’ (space) has been specified and that the first and third columns are selected from the file. [kevin@icarus kevin] $ cut —d” “ —cl-. coir) (erry i} Lu Figure 20: Using the ‘cut’ command with the ‘-c’ option In Figure 20, we find that the delimiter ‘ ‘ (space) has been specified and that the first three characters are selected from the file. 5.5.10 The ‘paste’ ymmand Syntax paste [options] [filename] The paste command works as the inverse of the cut command. It is used to merge lines of files. rok) us kevin] $ cat dat2 Sener te 21: Using the ‘paste’ command In Figure 21, the user is bringing together two files “datl” and ‘dat2” with the delimite separating them. Each line of the the first file ‘datl” is read , the specified delimiter ‘:’ is added to the end of the line from the first file and the corresponding line from the second file is added after the delimiter. 5.6 The Redirection Operators When we issue a command, such as ‘Is’, the output appears on the screen which is the standard output. But if we wish, we can redirect this output elsewhere. This is done by using the (redirection operator) character. This can redirect the output to a file. ome Oe Cor eee) orc Link [kevin@icarus kevin]$ Figure 22: Listing the contents of a directory Now let us redirect the output of the ‘Is’ command to a file. [kevin@icarus kevin] § cat file_list ere Dr rey rad ene) ue res pure fem Figure 23: Redirecting the output of ‘Is’ The ‘Is’ command normally sends its output to the monitor, which is the standard output file. In Figure 23, the redirection operator ‘>’ redirects the output of ‘Is’ to a file called ‘file_list’. The contents of the file ‘file_list’ are then displayed using the ‘cat’ command. So we see that both the commands effectively do the same thing. Now suppose we were to redirect the contents of some file called ‘Donald’ to ‘file_list’ then the earlier data would get overwritten, To prevent this, we can use ‘>>’ redirection operator. This appends the output to the file. This means that the earlier data is not destroyed and the contents of file ‘Donald’ are added at the end of this data. [earn kee mint eee koe ke {kevin@icarus kevin] $ cat Donald this is the contents of a file called Donald [kevin@icarus kevin] $ cat Donald >> file.list Ce Oot eee elem tg eR ems PU CU eR ees Figure 24: Appending the contents of a file to another file Most of the commands and filters take their input from the keyboard, which is the standard input We can make these commands take their input from a file by using the redirection operator Figure 25: A program taking its input from a file The ‘sort’ command like most commands, takes its input from the standard input file which is the keyboard. We can use the redirection operator to make ‘sort’ take its input from a file the output on the standard output file. \d display If an error occurs during the execution of command, then an error message is displayed on the screen which is the standard error file. We can redirect these error messages into a file or to the ‘/dev/null’ which is called the ‘trash can’. Any file or output send to this file is simply ignored. This is done in the following way: PRTC eeern ec AAU) ULE UAC SMR Lecce tee ccA AOI Figure 26: Redirecting the standard output to a file This tells the computer to find the file called ‘quake’. Error messages that are generated are sent to ‘/dev/null’. This leaves the screen unchanged. In some cases, we may require the error messages for debugging purposes. In such cases the error messages may be redirected to a file, which can be read later. This is shown in the following Figure Ee cuenta cued Figure 27: Redirecting the standard error to a file This will send all the error messages to a file called *Errors’ 5.7__Using Pipes Often we have to use the output of a program as the input of another. We can do so clumsily using redirection operators ‘>’ or ‘>>" A better method of performing the same is to make use of a mechanism called ‘pipes’. A ‘pipe’ connects the output of a program to the input of another program. The concept is similar to that of a pipeline that connects two water tanks. You can always have a clumsy method of transferring water from one reservoir to another by using a bucket. But a more elegant method is by using a pipeline. Often, if you have a large number of files, the command ‘Is’ is not very beneficial as the files just scroll down your screen before you can even read them. So to prevent that from happening we use a pipe. ‘I’ represents a pipe. Figure 28 illustrates the use of the ‘pipe’ operator. [kevin@icarus kevin]-$. Is lmore Figure 28: Redirecting the output of ‘Is’ to the ‘more’ command The ‘more’ command is a filter for paging through text one screen at a time. In Figure 28, the output of ‘Is’ is piped to ‘more’. The ‘more’ program ensures that we get the output one page at a time. Suppose we want to check the users logged in, in alphabetical order. To check the users logged in, we use the ‘finger’ command and to sort in alphabetical order we use the ‘sort’ command. Therefore the command to get the list of users logged in an alphabetical order is: [kevin@icarus kevin] $ fingerlsort Figure 29: Redirecting the output of ‘finger’ to the ‘sort’ command The Shell and Shell Scripts - Part II 11.1 Introduction This session introduces the student to some of the operators available in Linux. The iterative and conditional statements in Linux are also discussed. 11.2 Arithmetic Operators Arithmetic operations can be performed on numbers and variables containing numbers using the arithmetic operators available in the shell. All variables in Linux are treated as sequences of characters. Even numbers are recognised as sequences of characters and not as their numerical identity. Thus, the number ‘98° is considered to be, the character ‘9° followed by the character ‘8’. These character sequences of numbers have to be recognised by the shell. The ‘expr’ command does this conversion, making available the character sequences for arithmetical operations. The user must be careful while using the ‘expr’ command as it expects a space to be present before and after an ‘operator. The arithmetic operators available in Linux are Operator ( + Addition - Subtraction Division %__* _ | Modulus Operator (Remainder) ¥ ‘Multiplication Table 1: List of arithmetic operators In the case of multiplication the ‘*” character must be prefixed with the ‘V’ character. rus kevin] $ value= expr 60 + 40 Pe eRe [kevin@icarus kevin] $ expr 6 24 [kevin@icarus kevin] $ Figure 1: Using the ‘expr’ command In Figure 1, the ‘expr’ command is used to carry out arithmetic operations. The arithmetic operations can be carried out and the results stored in variables. In such cases, command substitution is used to store result of operations in the variables. @eThe grave quotes have to be used to store the resulis returned after the execution of a| program & a 1. Why is the ‘\’ character used to prefix the ‘*’ multiplication operator? of a Command 11,3 _ Exit Statu Linux allows users to keep track of the status of the previously executed program. The shell stores the status of the previous executed program whether it had successfully executed or if it had failed. TR eae LL NR Rg [kevin@icarus kevin] $ echo $? i Ge Ary ker Ta Ce Cee tena ted eer ne keen fn 5 B [kevin@icarus kevin] $ Figure 2: Using the ‘$2’ command In Figure 2, the user is trying to display the contents of a non existent file. This causes the shell to display an error message. Every command returns a value after execution to the shell in which it was executed. This value is referred to as the exit status of the command. The value ‘0’ implies successful completion of the command while the value ‘1’ implies that the command was not successfully carried out. This exit status of a command is stored in the system variable “S?" which has been used in Figure 2. The “$2” system variable is useful in shell scripts. The command executed returns a zero value on successful completion and a non-zero value on unsuccessful completion. 11.4 The ‘test? Command The ‘test’ evaluates the condition on the right side and returns a true or a false exit status, This return value is based on the condition specified being satisfied or not. The ‘test’ command can be used to and compare numbers, strings and file attributes. 115 _ Numeric Comparision The ‘test’ command can do the normal numerical comparison with the following options. [Option Example Purpose -eq__| test $n -eq $n2_| Check if values of two variables are equal -ne___| test $nil-ne $n2_| Check if values of two variables are not equal |-ge__| test §nl-ge $n2_| Check if values of one variable is greater than or equall to the other ‘le ___| test §nl “te $n2_| Check if values of one variable is less than ot equal to the other -gt__| test $n “gt $n2__[ Check if values of one variable is greater than the other -lt test $nl It $n2_| Check if values of one variable is less than the other Table 2: List of Numerical Evaluation Operators 11.6 _ String Comparison The ‘test’ command can do the string comparison with the following options [ Option Example Purpose = test $strl = $str2_| Check if values of two variables are equal 1 test $strl 1= $str2 | Check if values of two variables are not equal [=z test ~z $strl Check if value of the string is zero length n test —n $strl Check if values of the string is not zero length. Table 3: List of String Evaluation Operators 1. What is the difference between $strl=$str2 and $str1 = $str2? 11.7__ File Comparision ‘The ‘test’ command can query a file and examine its attributes. Option Purpose mR Check if a file exists and is non empty. ef Check if a file exists and is a regular file -d Check if a file exists and is a director [Option Purpose ¢ Check if file exists and i -b Check if a file exists and is block + | Check ifa file exists and is readable. -w Check if a file exists and is writable. x Check if a file exists and is executable. Table 4: List of File Evaluation Operators [test -r/home/kevin/estfile 11.8 Control Statements The shell script is a sequence of commands in a text file. The commands in the shell script are executed, The execution of commands can be controlled by using certain control statements These control statements determine the flow of execution of the commands in the shell script. The control statements are of two types, one is the ‘conditional’ statement and the other is the iterative’ statement. Conditional statements determine whether a block of statements is to be executed or not based on the result of the specified condition, 11.9 The ‘if... then ... fi? Construct The elementary conditional statement is the ‘if ... then .. fi” construct. Syntax: if (condition) then command(s) fi The ‘if’ command tests a condition and the condition return a result. If the condition is satisfied, then the block of statements between the ‘then’ and the ‘fi’ are executed. If the condition is not satisfied, the set of statements is skipped and the next statement outside the block is executed. {kevin@icarus kevin] $ cat chk_if else echo “Enter your name erry if test $LOGNAME = $n ftir Ceca TC Orece fi [kevin@icarus kevin] $ sh chk_if_el iors Pema Wenig [kevin@icarus kevin] $ Figure 3: Using the ‘if..then..fi’ condition In the above shell script, the user is named to key in a name. This name is compared and checked if itis the user’s name, If it is so, then a message is displayed. 11.10 Conditional Operators Multiple commands can be combined and executed using the ‘&é&? (‘AND’) and ‘I’ COR’) operators. These are called the conditional operators as they help in combining commands and carry out commands based on the conditions applied. The ‘&&’ operator combines the execution of two commands. The command on the right side of the *&&’ operator is executed only on the successful completion of the command on the left side of the ‘&&’ operator. arus kevin] $ cat chk_and aa Pa a Lie te UPd SETS} Teammore ne ary Rens A ET ce rence [kevin@icarus kevin] $ igure 4: Using the ‘&&’ conditional operator In Figure 4, the shell script verifies the contents of ‘namel’ and ‘name2’ and displays the message “Match found”. This multiple checking is done using one “if* condition. If either of the two variables had a value other than “Henry” or “Sam” the message would not have been displayed. The ‘Il’ conditional operator also combines commands such as the ‘&&’ operator. If the command on the left side of the fails to execute, the ‘I’ operator tries to execute the command on the right side. The ‘Il’ conditional operator takes on either of the commands supplied and tries to execute any one of them as the following figure shows. [kevin@icarus kevin] $ cat chk_or Pr Da Cn] Pens if test $namel = "Henry" || test $name2 ira Pee ATCO CTT fi Terre ea cary Ree aes Match found ene et ed igure 5: Using the ‘||’ conditional operator In Figure 5, note the differences in using the ‘&&’ and ‘lI’ conditional operators. The *&&' operator expects both the commands on either side of the ‘&&’ operator to succeed in execution to allow the ‘if’ condition to succeed. The ‘I!’ operator on the other hand tries to execute any of the commands on either side of the ‘II’ operator and allows the ‘if? operator to succeed if any of them succeeds in execution Multiple test checks can also be carried out using the following operators. [Option TaPupoe Lt The negation operator The ‘and’ operator The ‘or’ operator ‘Table 5: List of Logical Operators [kevin@icarus kevin] $ cat ch! era i faa Cea ROM eR fi [kevin@icarus kevin] $ sh chk_not File filet does not exi iene ut [kevin@icarus kevin] $ cat chk_and1 eee ome ea) fits) Ce ORO Reel eRe a fi- Ome a oR oon aed i bia OTR ae Lyd [kevin@icarus kevin] $ cat chk_orl eee mm aial a P ira roar SRS eee Lo rus kevin] $ sh chk_orl TOTES (emcee rn ny Figure 7: Using the ‘-a’ anmd ‘-o” operators The ‘test’ command can be replaced with the ‘[ be replaced with ‘[ $sirl = $str2 | braces. The ‘test $strl = $str2’ command can Note that every ‘test’ operator is separated before and after by a space 11.11 The ‘else’ Construct The ‘else’ construct is used to execute an alternate block of commands on the ‘if’ condition not being satisfied [kevin@icarus kevin] $ cat chk_if_else erent eC arnt Tits if test $LOGNAME = $name Pita) echo “Invalid User Name” [kevin@icarus kevin] § sh chk_if_else RTO aE Wenig [kevin@icarus kevin] $ Figure 8: Using the ‘if..then..els. condition In the above example, if the name supplied is not the user’s name an error message is generated. This was not possible in the earlier example. 11.12 The ‘elif? Construct The ‘elif’ construct is used to create multiple conditional statements (multiple else). Syntax if condition! then command(s) elif condition2 then command(s) fi If the condition! is satisfied, then the commands between the first ‘then’ and ‘elif? are executed and the control goes to the statement following the fi. Otherwise, if the condition2 is satisfied, then the commands between the second ‘then’ and ‘elif are executed and the control goes to the statement following the ‘fi’. [kevin@icarus kevin] $ cat chk_if_else_elif Peice tires er Neco armen te te hour="date |eut -c12,13 if test hour ~ge 0 -a—e 11 frou) echo “Good Morning’ elif test hour ~ge 12 -a-le 17 fra echo “Good Afternoon” ont _ echo “Good Evening” [kevin@icarus kevin] $ sh chk_if_else_elif Good Morning (Cement sin ky Figure 9: Using the ‘if..then. Ise..fi? condition 11.13 The ‘case? Command Be igs Syntax case value in pattern!) command(s);: pattern2) command(s);; pattern3) command(s);; pattern4) command(s);; ) esac The case command compares a single value against other values and executes commands when a match is found. The value is compared to the patterns until a match is found. When a match is found, the commands listed after the matching value, up to the double semicolons are executed On encountering the double semicolons, the case statement is terminated and control passed to the statement following the ‘esac’. If none of the patterns match the value then the default commands given after the “*)’ are executed. The default choice is commands following the *” The problems of indentation. ‘case’ control statement is used to replace the ‘if ...clif...fi’ statements, which leads to Sor rh is men meme # Shell script for printing calendar case $1 in RPT oso AULD LER ST Apriapr) m=4;; APN ep BT ed BTU eee Re ee eer yer Octoct) m=10;; NOY Op Led | Dee|dec) m=1253 a Damar) echo “Please enter months (Jan - Dec) only”;; Terre AOR See men Meee en REO) SONOMA naar i ee Weird Comer Ree ey SUA CMe eee 2324 25 26 27 28 29 Ri | [kevin@icarus kevin] $ ure 10: Using the ‘case..esac’ conditional operator he ‘while’ Iterative Construct while test condition d command: done The ‘while’ command is another type of iterative statement. Here, when the condition is executed and is satisfied; the commands between the ‘do’ and the ‘done’ are executed. The condition is evaluated repeatedly until the condition is not satisfied. The iterative process is now terminated and the statement following the ‘done’ statement is executed. Rr emene Pea ete earl Senet ie Py NLR eae ct ee echo “The value of iis $i” CER aCe Be rs echo “The total is $total” RONG are Rue a) PEE (eounGe Laney Figure 11: Using the ‘while’ iterative statement 11.15 The ‘until’ Command , Syntax: While test condition do | commands done The “until” command is similar to the ‘while’ command. It executes the iterative statement as long as the condition following the ‘until’ return a non-zero exit status. When the condition is not satisfied, the iterative process is terminated Tey ere kere mee ; # until samp! rin ore) De ee do num="expr $num + 1 Core ee aye shift rod [kevin@icarus kevin] $ until_example1 John Smith Janet York William A\ Teeter ny eer meena) eee rsa er reese Crs eee ee Caan) SUC [emote ark Figure 12: Using the ‘until iterative statement 11.16 The ‘for’ Iterative Construct Syntax: for var in word] word2 word3 word4 ... wordn do command(s) done The ‘for’ loop executes a set of commands for a specified number of times. The commands between the ‘do’ and the ‘done’ form the body of the loop. This loop is executed, as many times as the number of words specified after the ‘in’, When the loop is first executed, the first word, ‘word!’ is assigned to the variable ‘var’ and the commands between ‘do’ and ‘done’ are executed. Then the next word is assigned and again the loop is executed. This goes on until all the words in the list are exhausted [kevin@icarus kevin] $ cat for_example ey Oe Res rus kevin] $ chmod 700 for_example PR ioaeci aS Figure 1 sing the ‘for’ iterative statement re 13, the list (1,2,3,4) is given along with the ‘for’ statement, The ‘for’ statement picks up each item from the list and displays it The first line in the shell script (‘#!/bin/bash’) create: of the shell and passes the shell script commands to it for processing. The execute perm s ided to the permissions of the shell script file. This is done using the ‘chmod’ command. Cra On CTS [kevin@icarus kevin] $ for_example2 | 234 1 [kevin@icarus kevin] $ Figure 14: Using the ‘for’ iterative statement 14 takes its arguments from the command li Tey Tet Prot its [kevin@icarus kevin] $ for_example4 1 23 4 PO Ree PO ORL RSMo Figure 15: Using the ‘for’ iterative statement The above program picks out the filenames from a file and displays the contents of each file [kevin@icarus kevin] $ cat for_exampleS OE iat cit Tran exampleS Anna John Kevin Rudolph in) ro eon USRAL GLU SAL Figure 16: Using the ‘for’ iterative statement In Figure 16, the ‘in’ keyword is missing from the ‘for’ statement. The shell script picks up the values from the keyboard. [kevin@icarus kevin] $ cat for_example6 ed mn cn RT ra [kevin@icarus kevin] $ Figure 17: Using the ‘for’ iterative statement In Figure 17, the ‘for’ statement picks up the filenames from the current directory and displays the contents of each file because ‘*’ means ‘all files’ to the shell. 11.17 The ‘break’ Command Syntax while test condition do break; done The ‘break’ command is used to exit from an iterative process and not from the shell script. Whe the “break” statement is encountered the control is sent out of the iterative process and the first statement after the done is executed. [kevin@icarus kevin] § cat break_example1 PA ete ea ys SME OT Pac ct Pe Liaccran | fra) echo “User name is encountered. Loop Stopped” ers fi echo “The $num argument is $1” eid CS [kevin@icarus kevin] $ until_example1 John Smith kevin Janet York William Anna ete The 2 argument is Smith Oe e eect cr Rae eS rsct [kevin@icarus kevin] $ Figure 18: Using the ‘break’ command 11.18 The ‘continue’ Command while test condition do continue done The ‘continue’ command skips the remaining commands in the iteration but the execution of the iterative process continues as normal. UO a oh eetsnce ees erent ys oe) ez ne num="expr $num + 1 if test $1 = $LOGNAME furan Cra Ca CORR ey Ott else eae MIR TE rca oa fi arr Crd [kevin@icarus kevin] $ until_example! John Smith kevin Janet York William Anna emerson Peer eer fremuanentncr Recetas aie ment is York Beko en tT) See eee [kevin@i Boies Figure 19: Using the ‘continue’ command 11.19 Shell Functions Normally execution of shell scripts involves invoking an instance of the shell and the commands in the shell script are executed by this instance of the shell. Shell functions by contrast the commands in the function in the current instance of the shell. Shell functions can be plac a shell scripts and can be called more than once. Shell functions reduce duplication of code in the shell scrip [kevin@icarus kevin] $ hellol() i echo “The argument passed is $1 ) [kevin@icarus kevin] $ hellol Thomas Teen ow tone (USL aS SLL Figure 20: Executing the shell function from the shell prompt In Figure 20, the shell function is k n at the shell prompt. The shell function takes in an argument and displays its value imarn cn kk nts Sr0t ens Wes Cote ecru n rcae p>) echo “Designation is Accountant” Rss Ce estar mre a SSMS hs (ne ecru ecco y desg 1 [kevin@icarus kevin] $ bash shfunc 1 {kevin@icarus kevin] $ Figure 21: Using the ‘continue’ command Consider the shell script in Figure 21. The code snippet receives a number as input. This number is deciphered and the appropriate designation is displayed

You might also like