1. Trang chủ
  2. » Công Nghệ Thông Tin

Unix Shell Programming Third Edition phần 4 pptx

69 617 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 69
Dung lượng 1,36 MB

Nội dung

A Program to Add Someone to the Phone Book Let's continue with the development of programs that work with the phonebook file. You'll probably want to add someone to the file, particularly because our phonebook file is so small. You can write a program called add that takes two arguments: the name of the person to be added and the number. Then you can simply write the name and number, separated from each other by a tab character, onto the end of the phonebook file: $ cat add # # Add someone to the phone book # echo "$1 $2" >> phonebook $ Although you can't tell, there's a tab character that separates the $1 from the $2 in the preceding echo command. This tab must be quoted to make it to echo without getting gobbled up by the shell. Let's try out the program: $ add 'Stromboli Pizza' 973-555-9478 $ lu Pizza See if we can find the new entry Stromboli Pizza 973-555-9478 So far, so good $ cat phonebook See what happened Alice Chebba 973-555-2015 Barbara Swingle 201-555-9257 Liz Stachiw 212-555-2298 Susan Goldberg 201-555-7776 Susan Topple 212-555-4932 Tony Iannino 973-555-1295 Stromboli Pizza 973-555-9478 $ Stromboli Pizza was quoted so that the shell passed it along to add as a single argument (what would have happened if it wasn't quoted?). After add finished executing, lu was run to see whether it could find the new entry, and it did. The cat command was executed to see what the modified phonebook file looked like. The new entry was added to the end, as intended. Unfortunately, the new file is no longer sorted. This won't affect the operation of the lu program, but you can add a sort to the add program to keep the file sorted after new entries are added: $ cat add # # Add someone to the phonebook file version 2 # echo "$1 $2" >> phonebook sort -o phonebook phonebook $ Recall that the -o option to sort specifies where the sorted output is to be written, and that this can be the same as the input file: $ add 'Billy Bach' 201-555-7618 $ cat phonebook Alice Chebba 973-555-2015 Barbara Swingle 201-555-9257 Billy Bach 201-555-7618 Liz Stachiw 212-555-2298 Stromboli Pizza 973-555-9478 Susan Goldberg 201-555-7776 Susan Topple 212-555-4932 Tony Iannino 973-555-1295 $ So each time a new entry is added, the phonebook file will get re-sorted. A Program to Remove Someone from the Phone Book No set of programs that enable you to look up or add someone to the phone book would be complete without a program to remove someone from the phone book. We'll call the program rem and have it take as its argument the name of the person to be removed. What should the strategy be for developing the program? Essentially, you want to remove the line from the file that contains the specified name. The -v option to grep can be used here because it prints lines from a file that don't match a pattern: $ cat rem # # Remove someone from the phone book # grep -v "$1" phonebook > /tmp/phonebook mv /tmp/phonebook phonebook $ The grep writes all lines that don't match into the file /tmp/phonebook. [1] After the grep is done, the old phonebook file is replaced by the new one from /tmp. [1] /tmp is a directory on all Unix systems that anyone can write to. It's used by programs to create "temporary" files. Each time the system gets rebooted, all the files in /tmp are usually removed. $ rem 'Stromboli Pizza' Remove this entry $ cat phonebook Alice Chebba 973-555-2015 Barbara Swingle 201-555-9257 Billy Bach 201-555-7618 Liz Stachiw 212-555-2298 Susan Goldberg 201-555-7776 Susan Topple 212-555-4932 Tony Iannino 973-555-1295 $ rem Susan $ cat phonebook Alice Chebba 973-555-2015 Barbara Swingle 201-555-9257 Billy Bach 201-555-7618 Liz Stachiw 212-555-2298 Tony Iannino 973-555-1295 $ The first case, where Stromboli Pizza was removed, worked fine. In the second case, however, both Susan entries were removed because they both matched the pattern. You can use the add program to add them back to the phone book: $ add 'Susan Goldberg' 201-555-7776 $ add 'Susan Topple' 212-555-4932 $ In Chapter 8, "Decisions, Decisions," you'll learn how to determine whether more than one matching entry is found and take some other action if that's the case. For example, you might want to alert the user that more than one match has been found and further qualification of the name is required. (This can be very helpful, because most implementations of grep will match everything if an empty string is passed as the pattern.) Incidentally, before leaving this program, note that sed could have also been used to delete the matching entry. In such a case, the grep could be replaced with sed "/$1/d" phonebook > /tmp/phonebook to achieve the same result. The double quotes are needed around the sed command to ensure that the value of $1 is substituted, while at the same time ensuring that the shell doesn't see a command line like sed /Stromboli Pizza/d phonebook > /tmp/phonebook and pass three arguments to sed rather than two. ${n} If you supply more than nine arguments to a program, you cannot access the tenth and greater arguments with $10, $11, and so on. If you try to access the tenth argument by writing $10 the shell actually substitutes the value of $1 followed by a 0. Instead, the format ${n} must be used. So to directly access argument 10, you must write ${10} in your program. The shift Command The shift command allows you to effectively left shift your positional parameters. If you execute the command shift whatever was previously stored inside $2 will be assigned to $1, whatever was previously stored in $3 will be assigned to $2, and so on. The old value of $1 will be irretrievably lost. When this command is executed, $# (the number of arguments variable) is also automatically decremented by one: $ cat tshift Program to test the shift echo $# $* shift echo $# $* shift echo $# $* shift echo $# $* shift echo $# $* shift echo $# $* $ tshift a b c d e 5 a b c d e 4 b c d e 3 c d e 2 d e 1 e 0 $ If you try to shift when there are no variables to shift (that is, when $# already equals zero), you'll get an error message from the shell (the error will vary from one shell to the next): prog: shift: bad number where prog is the name of the program that executed the offending shift. You can shift more than one "place" at once by writing a count immediately after shift, as in shift 3 This command has the same effect as performing three separate shifts: shift shift shift The shift command is useful when processing a variable number of arguments. You'll see it put to use when you learn about loops in Chapter 9, "'Round and 'Round She Goes." Exercises 1: Modify lu so that it ignores case when doing the lookup. 2: What happens if you forget to supply an argument to the lu program? What happens if the argument is null (as in, lu "")? 3: The program ison from this chapter has a shortcoming as shown in the following example: $ ison ed fred tty03 Sep 4 14:53 $ The output indicates that fred is logged on, while we were checking to see whether ed was logged on. Modify ison to correct this problem. 4: Write a program called twice that takes a single integer argument and doubles its value: $ twice 15 30 $ twice 0 0 $ What happens if a noninteger value is typed? What if the argument is omitted? 5: Write a program called home that takes the name of a user as its single argument and prints that user's home directory. So home steve [...]... 8 10:06 wilma tty03 Jul 8 12:36 barney tty 04 Jul 8 14: 57 betty tty15 Jul 8 15:03 $ who | grep barney barney tty 04 Jul 8 14: 57 $ echo $? Print exit status of last command (grep) 0 grep "succeeded" $ who | grep fred $ echo $? 1 grep "failed" $ echo $? 0 Exit status of last echo $ Note that the numeric result of a "failure" for some commands can vary from one Unix version to the next, but success is always... arguments because the shell ate up the four spaces in blanks In the second case, test got one argument consisting of four space characters; obviously not null In case we seem to be belaboring the point about blanks and quotes, realize that this is a sticky area that is a frequent source of shell programming errors It's good to really understand the principles here to save yourself a lot of programming headaches... argument is identical to the third argument and returns a zero exit status if it is and a nonzero exit status if it is not The exit status returned by test is then tested If it's zero, the commands between then and fi are executed; in this case, the single echo command is executed If the exit status is nonzero, the echo command is skipped It's good programming practice to enclose shell variables that are... to see whether a shell variable has a null value with the third operator listed in Table 8.1: test "$day" This returns true if day is not null and false if it is Quotes are not necessary here because test doesn't care whether it sees an argument in this case Nevertheless, you are better off using them here as well because if the variable consists entirely of whitespace characters, the shell will get... pipe So in who | grep fred the exit status of the grep is used by the shell as the exit status for the pipeline In this case, an exit status of zero means that fred was found in who's output (that is, fred was logged on at the time that this command was executed) The $? Variable The shell variable $? is automatically set by the shell to the exit status of the last command executed Naturally, you can... $user is not logged on will be displayed $ who Who's on? root console Jul 8 10:37 barney tty03 Ju1 8 12:38 fred tty 04 Jul 8 13 :40 joanne tty07 Jul 8 09:35 tony tty19 Jul 8 08:30 lulu tty23 Jul 8 09:55 $ on pat pat is not logged on $ on tony tony is logged on $ Another nice touch when writing shell programs is to make sure that the correct number of arguments is passed to the program If an incorrect number... $ test $name = julio sh: test: argument expected $ Because name was null, only two arguments were passed to test: = and julio because the shell substituted the value of name before parsing the command line into arguments In fact, after $name was substituted by the shell, it was as if you typed the following: test = julio When test executed, it saw only two arguments (see Figure 8.1) and therefore issued... you wanted these two values to be considered equal, omitting the double quotes would have caused the shell to "eat up" the trailing space character, and test would have never seen it: $ day="monday " $ test $day = monday $ echo $? 0 $ True Although this seems to violate our rule about always quoting shell variables that are arguments to test, it's okay to omit the quotes if you're sure that the variable... if someone is logged on version 2 # user="$1" if who | grep "^$user " > /dev/null then echo "$user is logged on" fi $ who Who's on now? root console Jul 8 10:37 barney tty03 Jul 8 12:38 fred tty 04 Jul 8 13 :40 joanne tty07 Jul 8 09:35 tony tty19 Jul 8 08:30 lulu tty23 Jul 8 09:55 $ on lulu lulu is logged on $ on ann Try this again $ on What happens if we don't give any arguments? $ If no arguments are... String Operators As an example of the use of test, the following command returns a zero exit status if the shell variable name contains the characters julio: test "$name" = julio The = operator is used to test whether two values are identical In this case, we're testing to see whether the contents of the shell variable name are identical to the characters julio If it is, test returns an exit status of zero; . on root console Jul 8 10:06 wilma tty03 Jul 8 12:36 barney tty 04 Jul 8 14: 57 betty tty15 Jul 8 15:03 $ who | grep barney barney tty 04 Jul 8 14: 57 $ echo $? Print exit status of last command (grep) 0. 212-555-2298 Susan Goldberg 201-555-7776 Susan Topple 212-555 -49 32 Tony Iannino 973-555-1295 Stromboli Pizza 973-555- 947 8 $ Stromboli Pizza was quoted so that the shell passed it along to add as a single argument. ison ed fred tty03 Sep 4 14: 53 $ The output indicates that fred is logged on, while we were checking to see whether ed was logged on. Modify ison to correct this problem. 4: Write a program called

Ngày đăng: 13/08/2014, 15:21

TỪ KHÓA LIÊN QUAN