Download presentation
Presentation is loading. Please wait.
Published byMinna Keskinen Modified over 6 years ago
1
Command Substitution Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands. Command substitution is performed when a command is given as ´command´ Here command, can be a simple command, a pipeline, or a list. Caution - Make sure that you are using the backquote, not the single quote character, when performing command substitution. Command substitution is performed by the shell only when the backquote, or backtick, character, ´, is given. Using the single quote instead of the back quote is a common error in shell scripts leading to many hard to find bugs.
2
Command substitution is generally used to assign the output of a command to a variable. Each of the
following examples demonstrate command substitution: DATE=´date´ USERS=´who | wc -l´ UP=´date ; uptime´ In the first example, the output of the date command becomes the value for the variable DATE. In the second example, the output of the pipeline becomes the value of the variable USERS. In the last example, the output of the list becomes the value of the variable UP.
3
Arithmetic Substitution
In ksh and bash, the shell enables integer arithmetic to be performed. This avoids having to run an extra program such as expr or bc to do math in a shell script. This feature is not available in sh. Arithmetic substitution is performed when the following form of command is given: $((expression)) Expressions are evaluated according to standard mathematical conventions. Table 8.3 provides the available operators. The operators are listed in order of precedence.
4
Table 8.3 Arithmetic Substitution Operators Operator Description
/ The division operator. Divides two numbers and returns the result. * The multiplication operator. Multiples two numbers and returns the result. The subtraction operator. Subtracts two numbers and returns the result. + The addition operator. Adds two numbers and returns the result. () The parentheses clarify which expressions should be evaluated before others. You use the following command as an illustration of the operators and their precedence: foo=$(( ((5 + 3*2) - 4) / 2 )) After this command executes the value of foo to 3. Because this is integer arithmetic, the value is not 3.5, and because of operator precedence the value is not 6.
5
Flow Control if Statement
The if statement performs actions depending on whether a given condition is true or false. Because the return code of a command indicates true (return code is zero) or false (return code is nonzero), one of the most common uses of the if statement is in error checking. An example of this is covered shortly. The basic if statement syntax follows: if list1 then list2 elif list3 list4 else list5 fi
6
Both the elif and the else statements are optional
Both the elif and the else statements are optional. If you have an elif statement, you don't need an else statement and vice versa. An if statement can be written with any number of elif statements. The flow control for the general if statement follows: list1 is evaluated. 2. If the exit code of list1 is 0, indicating a true condition, list2 is evaluated and the if statement exits. 3. Otherwise, list3 is executed and its exit code is checked. 4. If list3 returns 0, list4 executes and the if statement exits. 5. If list3 does not return 0, list5 executes.
7
Because the shell considers an if statement to be a list, you can write it all in one line as follows: if list1 ; then list2 ; elif list3 ; then list4 ; else list5 ; fi ; Usually this form is used only for short if statements.
8
if uuencode koala.gif koala.gif > koala.uu ; then
Example A simple use of the if statement is if uuencode koala.gif koala.gif > koala.uu ; then echo "Encoded koala.gif to koala.uu" else echo "Error encoding koala.gif" Fi Look at the flow of control through this statement: 1. First, the command uuencode koala.gif koala.gif > koala.uu executes. This command is list1 in the general statement. 2. If this command is successful, the command uuencode Command Purpose Encodes a binary file for transmission using electronic mail. Syntax uuencode [ -m ] [ SourceFile ] OutputFile Description The uuencode command converts a binary file to ASCII data. This is useful before using BNU (or uucp) mail to send the file to a remote system. The uudecode command converts ASCII data created by the uuencode command back into its original binary form. The uuencode command takes the named SourceFile (default standard input) and produces an encoded version on the standard output. The encoding uses only printable ASCII characters, and includes the mode of the file and the OutputFile filename used for recreation of the binary image on the remote system. Use the uudecode command to decode the file. Flags -m Encode the output using the MIME Base64 algorithm. If -m is not specified, the old uuencode algorithm will be used.Parameters OutputFile Specifies the name of the decoded file. You can direct the output of the uuencode command to standard output by specifying /dev/stdout as the OutputFile.SourceFileSpecifies the name of the binary file to convert. Default is standard input.
9
executes and the if statement exits
executes and the if statement exits. This command is list2 in the general statement. 3. Otherwise the command echo "Error encoding koala.gif“ executes, and the if statement exits. This command is list5 in the general statement. You might have noticed in this example that both the if and then statements appear on the same line. Most shell programmers prefer to write if statements this way in order to make the if statement more concise. The majority of shell programmers claim that this form looks better.
10
Common Errors Three common errors can occur when using the if statement: Omitting the semicolon ( ;) before the then statement in the single line form Using else if or elsif instead of elif. Omitting the then statement when an elif statement is used. Writing if instead of fi at the end of an if statement.
11
Using test Most often, the list given to an if statement is one or more test commands, which are invoked by calling the test command as follows: test expression Here expression is constructed using one of the special options to the test command. The test command returns either a 0 (true) or a 1 (false) after evaluating an expression. A shorthand for the test command is the [ command: [ expression ] Here expression is any valid expression that the test command understands. This shorthand form is the most common form of test that you can encounter.
12
The types of expressions understood by test can be broken into three types:
File tests String comparisons Numerical comparisons
13
File Tests File test expressions test whether a file fits some particular criteria. The general syntax for a file test is test option file or [ option file ] Here option is one of the options given in Table 10.1 and file is the name of a file or directory. Look at a few examples of if statements that use the test command to perform file tests. Consider the following if statement: $ if [ -d /home/ranga/bin ] ; then PATH="$PATH:/home/ranga/bin" ; fi Here you are testing whether the directory /home/ranga/bin exists. If it does, append it to the variable PATH. Similar statements are often encountered in shell initialization scripts such as .profile or .kshrc.
14
Say you want to execute commands stored in the file $HOME/
Say you want to execute commands stored in the file $HOME/.bash_aliai if it exists. You can use the command $ if [ -f $HOME/.bash_aliai ] ; then . $HOME/.bash_aliai ; fi An improvement on this would be to test whether the file has any content and, if so, run the commands stored in it. You can change the command to use the - s option instead of the - f option to achieve this result: if [ -s $HOME/.bash_aliai ] ; then . $HOME/.bash_aliai ; fi Now the commands stored in the file $HOME/.bash_aliai execute if that file exists and has some content.
15
File Test Options for the test Command
Option Description -b file True if file exists and is a block special file. -c file True if file exists and is a character special file. -d file True if file exists and is a directory. -e file True if file exists. -f file True if file exists and is a regular file. -g file True if file exists and has its SGID bit set. -h file True if file exists and is a symbolic link. -k file True if file exists and has its "sticky" bit set. -p file True if file exists and is a named pipe. -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -u file True if file exists and has its SUID bit set. -w file True if file exists and is writable. -x file True if file exists and is executable. -O file True if file exists and is owned by the effective user ID.
16
String Comparisons The test command also supports simple string comparisons. There are two main forms: 1. Checking whether a string is empty 2. Checking whether two strings are equal The test options relating to string comparisons are given in Table 10.2. Table 10.2 String Comparison Options for the test Command Option Description -z string True if string has zero length. -n string True if string has nonzero length. string1 = string2 True if the strings are equal. string1 != string2 True if the strings are not equal.
17
Numerical Comparisons
The test command enables you to compare two integers. The basic syntax is test int1 operator int2 or [ int1 operator int2 ] Here int1 and int2 can be any positive or negative integers and operator is one of the operators given in Table If either int1 or int2 is a string, not an integer, it is treated as 0
18
Operator Description int1 -eq int2 True if int1 equals int2.
int1 -ne int2 True if int1 is not equal to int2. int1 -lt int2 True if int1 is less than int2. int1 -le int2 True if int1 is less than or equal to int2. int1 -gt int2 True if int1 is greater than int2. int1 -ge int2 True if int1 is greater than or equal to int2
19
Case The case Statement
The case statement is the other major form of flow control available in the shell. . The basic syntax is case word in pattern1) list1 ;; pattern2) list2 esac
20
Here the string word is compared against every pattern until a match is found. The list following the matching pattern executes. If no matches are found, the case statement exits without performing any action. There is no maximum number of patterns, but the minimum is one.
21
A case Statement Example
Consider the following variable declaration and case statement: FRUIT=kiwi case "$FRUIT" in apple) echo "Apple pie is quite tasty." ;; banana) echo "I like banana nut bread." ;; kiwi) echo "New Zealand is famous for kiwi." ;; Esac
22
The execution of the case statement is as follows:
1. The string contained in the variable FRUIT is expanded to kiwi. 2. The string kiwi is compared against the first pattern, apple. Because they don't match, you go to the next pattern. 3. The string kiwi is compared against the next pattern, banana. Because they don't match, you go 4. The string kiwi is compared against the final pattern, kiwi. Because they match, the following message is produced: New Zealand is famous for kiwi.
23
The while Loop The basic syntax of the while loop is while command do
list Done Here command is a single command to execute, whereas list is a set of one or more commands to execute. list is commonly referred to as the body of the while loop because it contains the heart or guts of the loop. The do and done keywords are not considered part of the body of the loop because the shell uses them only for determining where the while loop begins and ends.
24
The execution of a while loop proceeds according to the following steps:
1. Execute command. 2. If the exit status of command is nonzero, exit from the while loop. 3. If the exit status of command is zero, execute list. 4. When list finishes executing, return to Step 1.
25
Here is a simple example that uses the while loop to display the numbers zero to nine:
while [ $x -lt 10 ] do echo $x x=´echo "$x + 1" | bc´ done Its output looks like this: 1 2 . 9
26
The until Loop until command do list done
The while loop is perfect for a situation where you need to execute a set of commands while some condition is true. Sometimes you need to execute a set of commands until a condition is true. A variation on the while loop available only in ksh and bash, the until loop provides this functionality. Its basic syntax is: until command do list done Here command is a single command to execute, whereas list is a set of one or more commands to execute.
27
The execution of an until loop is identical to that of the while loop and proceeds according to the following steps: Execute command. 2. If the exit status of command is nonzero, exit from the until loop. 3. If the exit status of command is zero, execute list. 4. When list finishes executing, return to Step 1.
28
In most cases the until loop is identical to a while loop with list1 negated using the ! operator. For example, the following while loop x=1 while [ ! $x -ge 10 ] do echo $x x=´echo "$x + 1" | bc´ done is equivalent to the following until loop: x=1; until [ $x -ge 10 ] The until loop offers no advantages over the equivalent while loop. Because it isn't supported by all versions of the Bourne shell, programmers do not favor it. I have covered it here because you might run across it occasionally.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.