USP
UNIT- 6Essential Shell Programming Q1) Describe about the Input/output Statements in Shell.A1) Output Statements: The output statement in the Korn shell is the print command. Although the Korn shell also supports the echo command (inherited from the Bourne shell), we use print because it is faster and because there is the possibility that echo may become deprecated in a future version of the Korn shell.Syntax:
Example:$ time=4:30pm$ print "It is now $time"It is now 4:30pm$ time = 4:30pmSprint "it is now" StimeIt is now 4:30pm The print command automatically adds a terminating newline after the last argument. If for some reason we don't want a newline, we can use the - n option. To help format the output, there are nine C-like escape codes that can be used. When using these codes, they must be enclosed in quotes.
Input statement: Reading data from a terminal or a file is done using the read command. The read command reads a line and stores the words in variables. It must be terminated by a return, and the input line must immediately follow the command.Syntax:
When the read command is executed, the shell reads a line from the standard input (keyboard or redirected file) and stores it in variables word by word. Words are characters separated by spaces or tabs. The first word is stored in the first variable, the second is stored in the second variable, and so forth. Another way of saying this is that the read command parses the input string (line) into words. If there are more words than there are variables, all the extra words are placed in the last variable. If there are fewer words than there are variables, the unmatched variables are set to a null value. Any value in them before the read is lost. The below example demonstrates the use of the read command. The first example demonstrates what happens when not enough words are input. The word is null. In the second example, there are too many words. After the read, we print the variables and then just the third so that we can see exactly what happens. In each case, the first word is separated from the second word by a tab, and the rest of the words are separated by one or more spaces.Example:$ read word1 word2 word3 Hello Hi$print word1Hello$print word2Hi$print word3Null $ read word1 word2 word3Hello Hi How Are You Doing$print word1Hello$print word2Hi$print word3How Are You Doing
Code | Usage |
\b | Backspace |
\c | No new line same as –n |
\n | New line |
\f | Form feed |
\r | Carriage return |
\t | Tab |
\v | Vertical Tab |
\\ | To print backslash |
\Oddd | Octal code for ascii character to be printed |
Q2) How is reading from a file done in Korn Shell?A2)Reading from a file: The Korn shell allows scripts to read from a user file. This is done with the stream descriptor option (-u). A stream descriptor is a numeric designator for a file. The standard streams are numbered 0, 1, and 2 for standard input, standard output and standard error.Each read command reads the next line from the file. There is no space between the option and the stream descriptor.$read u4 variable_nameQ3) What is Exit status of a command in Korn shell?A3)In the Korn shell, when a command is executed, it returns a value known as the exit status of the command. The exit status is stored in a shell variable with a name of (?). Like all named variables, the exit status is accessible by using its name ($ ?). If a command completes successfully, it returns a zero value which is interpreted as true; if it does not complete successfully, it returns a nonzero value, which is interpreted as false.Syntax:
Example: $ Is file*File1 file2 file3.bak$ print $?0$is noneCannot access none. No such file or directory.$ print $?
Q4) Describe about the eval command in Korn Shell.A4)The eval.command is used when the Korn shell need to evaluate a command twice before executing it. To understand this, let's look at an example. To generalize a segment of code, we need to store the name of a variable in a second variable and then use the print command to display the value of the original variable. This permits us to reuse the code by placing a different variable in the second one, allowing us to change the variable that is being displayed. The concept is simple the direct approach doesn't work. It fails because the command is evaluated only once$x=23$y=x$print xxThe above example returns x as an output and not its value. Hence eval command is to be used.$x=23$y=x$print eval \$$Y23When the eval command is executed, it first evaluates $y, which generates the string value $x. The second evaluation then evaluates the variable $x, which produces the correct effect, the printing of the variable stored in y.Q5) How is Command execution process carried out?A5)Command execution is carried out in six sequential steps. The six execution steps are recursive. This means that when the shell performs the third step, command substitution, the six steps are followed for the command inside the dollar-parentheses.1. Command Parsing: The shell first parses the command into words In this step, it uses whitespaces as delimiters between the words. It also replaces sequences of two or more spaces or tabs with a single space.2 Variable Evaluation: After completely parsing the command, the shell looks for variable names (unquoted words beginning with a dollar sign) When a variable name is found, its value replaces the variable name. 3. Command Substitution: The shell then looks for a command substitution. If found, the command is executed and its output string replaces the command, the dollar sign, and the parentheses. 4. Redirection: At this point, the shell checks the command for redirected files. Each redirected file is verified by opening it. 5. Wildcard Expansion: When filenames contain wildcards, the shell expands and replaces them with their matching filenames. This step creates a file list6. Path Determination: In this last step, the shell uses the PATH variable to locate the directory containing the command code. The command is now ready for executionExample: Look at the cat command. To show the whitespace characters, we use A to represent a space and to represent a tab. $cat →→$var→→→report*1> file3→2>file4 In the first step, the shell parses words. It replaces all tabs and multiple spaces with a single space. The result is shown in the next example. Because all tabs and spaces have been parsed, we show a space in the normal fashion $ cat $var report* 1>file 3 2>file4 The second step replaces the variable ($var) with its value, file*. The result is $ cat file* report* 1>file 3 2>file4 The third step is skipped because there is no command substitution. In the fourth step, the redirected files are handled: file3 is opened for output filed is opened for errors. In the fifth step, the shell expands the wildcards. The command is now: $ cat fileA fileB fileC report1 report2 1> file3 2> file4f. In the last step, the shell finds the /bin directory in the PATH variable. completes the command as in the next example: $ /bin/cat fileA fileB fileC report1 report2 1> file3 2> file4 Q6) Write about the Decision making statements in Korn shell.A6)The Korn shell has two different decision making statements that allows us to choose between different alternatives. The first, the if then - else statement, examines the data and chooses between two alternatives. For this reason, it is sometimes referred to as a two way selection. The second, the case statement, selects one of several paths by matching patterns to different strings. if - then - else statement : Every language has some variation of the if-then-else statement The only difference between them is what keywords are required by their syntax. The shell evaluates the exit status from the command following fi. When the exit status is 0, then the set of commands is executed. When the exit status is 1, the else set of commands is executed.Syntax:
if commandthencommandcommand elsecommand commandfi Example: Program to look at the time of day and print an appropriate greeting, such as "good morning" or "good evening. #!/bin/ksh# Script : gday.scrhour=$(date | cut-c 12-13)if (( hour <= 18))thenprint Good Morningelseprint Good Eveningfi$gday.scrOutput: Good Evening if without else : Often we make a test that requires action only if the test is true. No action is required if the test is false. In this case, we need a then statement without a matching else. When there is no false action, we simply omit the else(false) portion of the command.
Syntax:If commandthencommand commandfi Example: Program to determine whether a file exists and is readable. If it is, we cat the file. If the file doesn't exist, we do nothing# Script: Ifnoelse.scrIf [[ -r $1]]thencat $1fi$ifnoelse.scr file1Output: This is file1else without if : Although we can have an if-then-else statement without an else action, we cannot have one without a then action When there are no true actions in the if - then - else, we use what is called the null command for the true action. The null command is a colon (:). It does nothing but satisfy the requirement for a command in the then action.Syntax:if command then: elsecommandcommandfiNested if Statements: Each branch in the if-then-else statement can be any command including another if-then-else statement. When an if-then-else statement is found in either the true or false branch of an if-then else command it is called a nested if. This type of nesting is so common that a compact format, in which the if and the else are combined into a word called elif. While either the true or false action can be nested, it is more commonly the false action.Example: Program to grade a student according to the score scored following conditions.if (( score >=90) thengrade=Aelif ((score >=80))thengrade=Belif ((score >=70))thengrade=Celif ((score >=60)thengrade=D else grade=Fficase statement: The Korn shell implements multiway selection with the case statement. Given a string and a list of pattern alternatives, the case statement matches the string against each of the patterns in sequence. The first pattern that matches the string gets the action. If no patterns match, the case statement continues with the next command.
The case statement contains the string that is evaluated. It ends with an end case token, which is esac (case spelled backward). Between the start and end case statements is the pattern list. For every pattern that needs to be tested a separate pattern is defined in the pattern list. The pattern ends with a closing parenthesis Associated with each pattern is one of more commands. The commands follow the normal rules for commands with the addition that the last command must end in two semicolons. The last action in the pattern list is usually the wildcard asterisk, making it the default if none of the other cases match.
|
Q7) Describe about the command control loops in Korn Shell.A7)In a command-controlled loop, the execution of a command determines whether the loop body executes or not. There are two command controlled loops in the Korn shell: The while loop and the until loop. 1. while loop: The while loop is a basic command-controlled loop. It begins with while, which contains the loop command and loops as long as the command’s exit status is true (zero). When the exit status becomes false (nonzero) the loop terminates.Syntax:
2. until loop: The until loop works just like the while loop, except that it loops as long as the exit status of the command is false. In this sense, it is the complex of the while loopSyntax:
Example:#!/bin/ksh# script untla=0until [ $a -ge 101doecho $aa= ‘expr $a+1’done$ ksh untl01 234 5678910
|
Q8) What is Repeat loop in Korn Shell?A8)Repeat loop: The repeat loop is a very simple loop that executes one command specified number of times. It requires two parameters: the number of times to loop and a single command to be executed. The command must be simple; that is, it cannot have a pipe or other complex construct.Example: Script to demonstrate repeat loop#1/bin/ksh/ -f#Script : loopRepeat.scr set looper = 5repeat $looper echo Hello %loopRepeat.scrOutput:Hello HelloHelloHello HelloQ9) How is Debugging done in Korn Shell?A9)Whenever we write a script we must test it. Often multiple tests are necessary. Sometimes the tests don't deliver the expected results. In these cases, we need to debug the script. There are two Korn shell options that we can use to help debug scripts: the verbosity (verbose) option, and the execute trace (xtrace) option. The verbose option prints each statement that is syntactically correct and displays an error message if it is wrong. Script output, if any, is generated.The xtrace option prints each command, preceded by a plus (+) sign, before it is executed. It also replaces the value of each variable accessed in the statement. For example, in the statement y= $x, the $x is replaced with the actual variable value at the time the statement is executed. If the variable x contained 13, the display would be y=13. In a similar manner, expression values and test values are displayed. Combining the two options allows us to see the command first and then see it with a plus sign and all references to variables replaced by their values.We can use these debug commands in two ways: include the options in the script and call the script with them.$ cat dbugoptstVset -o verbosex=5((y = x+2))If (( y == 10 ))thenprint \$y contains 10elseprint \$y contains $y not 10fi while ((x !=0))doprint counting down : \$x is $x((x =x - 1))done$ ksh dbugoptstvx=5(y = x+2)) if(y== 10 ))thenprint \$y contains 10elseprint \$y contains $y not 10fi$y contains 7 not 10while ((x!=0))doprint counting down : \$x is $x((x = x- 1))donecounting down : $x is 5counting down : $x is 4counting down : $x is 3counting down : $x is 2 counting down : $x is 1 When the debug option is included in the script, we must edit it to remove the set command when we complete the debug sessions. We can avoid this extra step if we include the options on the command line. This requires that we invoke the Korn shell in the command.$ cat dbugoptstVset -o verbosex=5((y=x+2))if (( y == 10 ))thenprint \$y contains 10elseprint \$y contains $y not 10fi while ((x !=0))doprint counting down : \$x is $x((x = x - 1))done $ ksh - xtrace dbugoptstv+ x=5+ (( y = x+2 ))+ ((y == 10 ))+ print $y contains 7 not 10$y contains 7 not 10 + ((x != 0 ))+ print Counting down: $x is 5Counting down: $x is 5+ (( x = x - 1 ))+ ((x != 0))+ print Counting down: $x is 4Counting down: $x is 4+ (( x = x - 1 ))+ ((x != 0 ))+ print Counting down: $x is 3Counting down: $x is 3+ ((x = x-1 ))+ ((x != 0 ))+ print Counting down: $x is 2Counting down: $x is 2+ ((x =x-1))+ ((x != 0 ))+ print Counting down: $x is 1 Counting down: $x is 1+ ((x = x-1 ))+(( x != 0))
Q10) Write a korn shell program to find factorial of a given number..A10)echo "Enter the number:read factans=1counter=0while [ $fact -ne $counter ]docounter='expr $counter + 1’ans='expr $ans \* $counter’doneecho "The factorial of a given number is $ans"Output:Enter the number: 5The factorial of a given number is 120
0 matching results found