436 Chapter 9 ■ Writing Scripts, Configuring Email, and Using DatabasesAlthough launching several programs from one script can save time in starting your working environment and some other situations, scripts are also frequently used to run a series of programs that manipulate data in some way. Such scripts typically do notinclude the ampersands at the ends of the commands because one command must run after another or may even rely on output from the first. A comprehensive list of such commands is impossible because you can run any program you can install in Linux as a command in a script—even another script. A few commands that are commonly used in scripts include the following:Normal File Manipulation Commands The file manipulation commands, such as ls, mv, cp, and rm, are often used in scripts. You can use these commands to help automate repetitive file maintenance tasks.grep This command is described in Chapter 1. It locates files that contain specific strings.find Where grepsearches for patterns within the contents of files, finddoes so based on filenames, ownership, and similar characteristics. This command is described in Chapter 4.cut This command extracts text from fields in a file. It’s frequently used to extract variable information from a file whose contents are highly patterned. To use it, you pass it one or more options that specify what information you want, followed by one or more filenames. For instance, users’ home directories appear in the sixth colon-delimited field of the /etc/passwdfile. You can therefore type cut -f 6 -d “:” /etc/passwdto extract this information. The same command in a script will extract this information, which you’ll probably save to a variable or pass to a subsequent command via a pipe.sed This program is described in Chapter 1. It provides many of the capabilities of a conventional text editor but via commands that can be typed at a command prompt or entered in a script.echo Sometimes a script must provide a message to the user; echois the tool to accomplish this goal. You can pass various options to echoor just a string to be shown to the user. For instance, echo “Press the Enter key”causes a script to display the specified string.mail The mailcommand can be used to send email from within a script. Pass it the -s subjectparameter to specify a subject line, and give it an email address as the last argument. If used at the command line, you then type a message and terminate it with a Ctrl+D keystroke. If used from a script, you might omit the subject entirely, pass it an external file as the message using input redirection, or use a here document to pass text to the mailcommand as input. (Chapter 1 describes input redirection and here documents.) You might want to use this command to send mail to the superuser about the actions of a khởi động kịch bản hoặc một kịch bản mà chạy trên một cơ sở tự động. Lệnh này được mô tả trong chi tiết hơn sau đó trong chương này.Viết kịch bản 437Nhiều người trong số những lệnh này là cực kỳ phức tạp, và hoàn toàn mô tả chúng là vượt ra ngoài phạm vi của chương này. Bạn có thể tham khảo trang man các lệnh để biết thêm thông tin. Một vài trong số chúng được mô tả ở những nơi khác trong cuốn sách này.Ngay cả khi bạn có một nắm bắt đầy đủ về cách sử dụng một số lệnh bên ngoài quan trọng, chỉ cần thực hiện lệnh bạn có thể khi gõ chúng một dấu nhắc lệnh là tiện ích hạn chế. Nhiều tác vụ quản trị yêu cầu bạn phải thay đổi những gì bạn gõ một lệnh, hoặc thậm chí những gì lệnh bạn nhập, tùy thuộc vào các thông tin từ các lệnh khác. Vì lý do này, ngôn ngữ kịch bản bao gồm các tính năng bổ sung để giúp bạn thực hiện kịch bản của bạn hữu ích.Bằng cách sử dụng biếnVariablescan giúp bạn mở rộng các tiện ích của kịch bản. Một biến là một giữ chỗ trong một kịch bản Đối với một giá trị sẽ được xác định khi kịch bản chạy. Giá trị biến có thể được thông qua dưới dạng tham số kịch bản, tạo ra trong nội bộ để các kịch bản, hoặc chiết xuất từ các tập lệnh môi trường.Các biến được truyền đến các tập lệnh thường được gọi là tham số. Họ đang biểu diễn bằng một ký hiệu đôla ($) theo sau một số từ 0 đến 9-$0stands cho tên của Các kịch bản, $1is tham số đầu tiên để kịch bản, $2is thứ hai tham số, và như vậy. Để hiểu làm thế nào điều này có thể hữu ích, hãy xem xét việc thêm người dùng. Miêu tả trong chương 7, "Quản lý hệ thống," tạo tài khoản người dùng mới thường liên quan đến việc chạy hai lệnh — useraddand passwd. Bạn cũng có thể cần để chạy lệnh trang bổ sung, chẳng hạn như lệnh mà tạo ra bất thường người dùng thuộc sở hữu thư mục bên cạnh thư mục chính của người dùng.Shiftcommand thay đổi các tham số biến vì vậy mà những gì nào thông thường là $2becomes $1, điều gì sẽ là $3becomes $2, và như vậy. Thêm một số, như trong sự thay đổi 3, thay đổi các bài tập bằng số điện thoại của đơn vị. Shiftcommand không thay đổi $0variable, mặc dù. Bạn có thể sử dụng shiftin kết hợp với một vòng lặp (sau này, được mô tả trong "Bằng cách sử dụng vòng") để kiểm tra tất cả các tham số truyền cho một kịch bản, trong trường hợp của họ đặt hàng hoặc số là không rõ khi bạn viết kịch bản.Như là một ví dụ về làm thế nào một kịch bản với một biến tham số có thể giúp đỡ trong tình huống như vậy, xem xét danh sách 9.2. Kịch bản này tạo ra một tài khoản và thay đổi mật khẩu của tài khoản (bạn sẽ được nhắc nhở để nhập mật khẩu khi bạn chạy script). Nó tạo ra một thư mục trong cây /shareddirectory tương ứng với các tài khoản, và nó đặt một liên kết tượng trưng cho thư mục đó từ thư mục chính của người dùng mới. Nó cũng điều chỉnh quyền sở hữu và cấp phép trong một cách mà có thể hữu ích, tùy thuộc vào hệ thống của bạn sở hữu và cấp phép chính sách.438 chương 9 ■ viết kịch bản, cấu hình Email, và bằng cách sử dụng cơ sở dữ liệuListing 9.2: A script that reduces account-creation tedium#!/bin/shuseradd -m $1passwd $1mkdir -p /shared/$1chown $1.users /shared/$1chmod 775 /shared/$1ln -s /shared/$1 /home/$1/sharedchown $1.users /home/$1/sharedIf you use Listing 9.2, you need type only three things: the script name with the desired username and the password (twice). For instance, if the script is called mkuser, you can use it like this:# mkuser ajonesChanging password for user ajonesNew password:Retype new password:passwd: all authentication tokens updated successfullyMost of the scripts’ programs operate silently unless they encounter problems, so the interaction (including typing the passwords, which don’t echo to the screen) is a result of just the passwdcommand. In effect, Listing 9.2’s script replaces seven lines of commands with one. Every one of those lines uses the username, so by running this script, you also reduce the chance of a typo causing problems.Another type of variable is assigned within scripts—for instance, such variables can be set from the output of a command. These variables are also identified by leading dollar signs, but they’re typically given names that at least begin with a letter, such as $Addror $Name. (When values are assigned to variables, the dollar sign is omitted, as illustrated shortly.) You can then use these variables in conjunction with normal commands as if they were command parameters, but the value of the variable is passed to the command.For instance, consider Listing 9.3, which checks to see whether the computer’s router is up with the help of the pingutility. This script uses two variables. The first is $ip, which is extracted from the output of routeusing the grep, tr, and cutcommands. (These commands are described in Chapter 1.) When you’re assigning a value to a variable from the output of a command, that command should be enclosed in back-tick characters (`), which appear on the same key as the tilde (~) on most keyboards. These are notordinary single quotes, which appear on the same key as the regular quote character (“) on most keyboards. The second variable, $ping, simply points to the pingprogram. It can easily be omitted, with subsequent uses of $pingreplaced by the full path to the program or simply by ping(relying on the $PATHenvironment variable to find the program). Variables like this are sometimes used to make it easier to modify the script in the future. For instance, if you Writing Scripts 439move the pingprogram, you need only modify one line of the script. Variables that point to binaries can also be used in conjunction with conditionals to ensure that the script works on more systems—for instance, if pingwere called something else on some systems.Listing 9.3: Script demonstrating assignment and use of variables#!/bin/sh
ip=`route -n | grep UG | tr -s “ “ | cut -f 2 -d “ “`
ping=”/bin/ping”
echo “Checking to see if $ip is up...”
$ping -c 5 $ip
In practice, you use Listing 9.3 by typing the script’s name. The result should be the
message Checking to see if 192.168.1.1is up(with 192.168.1.1replaced by the computer’s default gateway system) and the output from the pingcommand, which should attempt
to send five packets to the router. If the router is up and is configured to respond to pings,
you’ll see five return packets and summary information. If the router is down, you’ll see
error messages to the effect that the host was unreachable.
Listing 9.3 is of limited practical use and contains bugs. For instance, the
script identifies the computer’s gateway merely by the presence of the
string UGin the router’s output line from route. If a computer has two routers defined, this won’t work correctly, and the result is likely to be a script
that misbehaves. The point of Listing 9.3 is not to be a flawless program
but to demonstrate how variables can be assigned and used.
Scripts like Listing 9.3, which obtain information from running one or more commands,
are useful in configuring features that rely on system-specific information or information
that varies with time. You can use a similar approach to obtain the current hostname (using
the hostnamecommand),
đang được dịch, vui lòng đợi..
