Shell script Automation

Source: Internet
Author: User
Tags split words
Shell script automation-general Linux technology-Linux technology and application information. For more information, see the following. List 1. Simple Shell script for synchronizing home directories across multiple computers

#! /Bin/zsh
For each machine (groucho chico harpo)
Rsync-e ssh -- times -- perms -- recursive -- delete $ HOME $ machine:
End


To use Listing 1 as a Shell script, you can save the preceding content to a file, such as simpleprop. zsh, and run chmod + x simpleprop. zsh to make the file executable. You can run the script by entering./simpleprop. zsh.
If you want to see how to expand each command in Z Shell, you can add the-x option to the script #! The end of a line (#-Exclamation point) is as follows:
#! /Bin/zsh-x


This script runs the rsync command on each computer in groucho, chico, and harpo, and replaces $ HOME with your home directory (for example,/HOME/joe ), replace $ machine with the computer name.
As shown in Listing 1, variables and script control structures such as loops make the script easier to write and maintain. If you want to include the fourth computer (such as zeppo) in the computer pool, you only need to add it to the list. If you must change the rsync command, such as adding another option, you only need to edit one instance. Like in traditional programming, you should also try to avoid cutting and pasting in Shell scripts.
Use appropriate parameters
Other Shell scripts require parameters, or a dynamic list of objects to be processed-files, directories, and computer names. For example, consider listing 2, which is a variant of the previous example. It allows you to use the command line to specify the computer you want to synchronize.

Listing 2. allow you to specify a variant of Listing 1 for the computer to be processed

#! /Bin/zsh
For each machine
Rsync-e ssh -- times -- perms -- recursive -- delete $ HOME $ machine:
End


Suppose you save Listing 2 in the name of synch. in zsh files, you must follow zsh synch. zsh moe larry curly calls the script to copy the home directory to another computer, larry and curly.
The list missing on the foreach row is not an input error: If you omit a list, the foreach structure processes the parameter list given on the command line. The command line parameter is also called the positional parameter, because the position of a parameter on the command line is usually very important in semantics.
For example, if you do not specify any parameters, listing 2 can use the existence or non-existence of location parameters to provide helpful usage information. The enhanced script is shown in listing 3.

Listing 3. Many scripts will provide helpful messages when no parameters are provided

#! /Bin/zsh
If [[-z $1 | $1 = "-- help"]
Then
Echo "usage: $0 machine [machine...]
Fi
Foreach machine
Rsync-e ssh -- times -- perms -- recursive -- delete $ HOME $ machine:
End


Each space-separated string on the command line is changed to a location parameter, including the name of the called script. Therefore, the command synch. zsh has only one location parameter $0. The synch. zsh -- help Command has two positional parameters: $0 and $1, where $1 is the string -- help.
Therefore, listing 3 indicates "if the first position parameter is null (the-z operator tests an empty string) or (represented by |) if the first parameter is '- help ', print the usage information ". (If you are writing a script at the beginning, you can consider providing the usage information in each script as a prompt. It reminds others-or even yourself, if you forget-how to use the script .)
The phrase [[-z $1 | $1 = "-- help"] is a condition of the if statement, but you can use the same condition clause as a command, and use it with other commands to control the stream through the script. See Listing 4. It enumerates all executable commands in your $ PATH and combines the conditions with other commands to perform the appropriate work.

Listing 4. LIST commands in $ PATH

#! /Bin/zsh
Directories = ('echo $ PATH | column-s': '-t ')
For directory in $ directories
Do
[[-D $ directory] | continue

Pushd "$ directory"

For file in *
Do
[[-X $ file &&! -D $ file] | continue
Echo $ file
Done

Popd
Done | sort | uniq


This script performs a considerable number of operations, which are divided into the following parts:
The first actual script line -- directories = ('echo $ PATH | column-s': '-t') -- creates an array of the specified directory. In zsh, you create data by placing parameters in parentheses, for example, directories = (...). In this example, the array element splits $ PATH at each colon (column-s ':') to generate a list of directories separated by spaces (column-t parameter).
For each directory in the list, the script tries to enumerate executable files in the directory. Steps 3 to 6 describe the process.
[[-D $ directory] | the continue line is an example of the so-called short-circuiting command. The short-circuiting command is terminated immediately when its logical conditions produce a definite result.
For example, [[-d $ directory] | the continue phrase uses the logical "or" (|) -- it first executes the first command, and the second command is executed only when the first command fails. Therefore, if an entry in $ directory exists and is a directory (-d operator), the test is successful, the evaluation ends, and the continue command (it skips the processing of the current element) it will never be executed.
However, if the first test fails, the next condition of the logic is executed or the continue is executed. (Continue always succeeds, so it usually appears at the end of the short-circuiting command ).
The Short-circuiting based on the Logical "and" (&) First executes the first command, and the second command is executed only when the first command is successful.
Pushd and the corresponding popd are used to switch to the new directory before processing and to the previous directory after processing. Directory stack is an ideal script technology for maintaining your location in the file system.
The internal for loop enumerates all files in the current working directory-Wildcard * (asterisk) matches all entries-and then tests whether each entry is a file. [[-X $ file &&! -D $ file] | the continue line indicates "If $ file exists and is an executable file and not a directory, process it; otherwise, execute continue ".
Finally, if all the preceding conditions are met, echo is used to display the file name.
Do you understand the last line of the script? You can send the output of most control structures to another unix Command-after all, Shell treats the control structure as a command. Therefore, the output of the entire script is transmitted through sort and uniq to generate a sorted list of letters of the unique command found in your $ PATH.
If you save Listing 4 to an executable file named listcmds. zsh, the output may be similar to the following:
$./Listcmds. zsh
[
A2p
AB
Ac
Accept
Accton
Aclocal


The short-circuiting command is very useful in scripts. It combines conditions and operations in a single command. And since every UNIX command returns a status code indicating success or failure, you can use any command as a "condition"-not just a test operator. According to the Conventions, zero (0) is returned for unix to indicate success, and non-zero is returned to indicate failure. The non-zero value reflects the error type.
For example, if you replace [-d $ directory] | continue with cd $ directory | continue, you can remove pushd and popd from listing 4. If the cd command is successful, it returns 0, and the evaluation of the logic "or" can end immediately. However, if cd fails, it returns a non-zero value and executes continue.
Do not delete. Archive!
Modern UNIX Shell-bash, ksh, and zsh-provides many control structures and operations to create complex scripts. Since you can call all unix commands to process data from one form to another, Shell script programming is almost as rich as programming in a complete language such as C or Perl.
You can use scripts to automate almost all personal or system tasks. Scripts can monitor, archive, update, upload, download, and convert data. A script can have only one row or contain countless subsystems. Tasks can be processed by scripts regardless of their size. In fact, if you view the/etc/init. d directory, you will see various Shell scripts that run the service each time you start the computer. If you have created a very useful script, you can even deploy it as a system-wide utility. You only need to put it in a directory on your $ PATH.
Let's create a utility to practice your new discoveries. The script myrm replaces the system's rm utility. Unlike deleting an object permanently, myrm copies the object to be deleted to an archive and names it uniquely so that you can locate it and then delete the original file. The myrm script is valid but simple, and you can add many miscellaneous functions. You can also write a wide range of unrm (unrm undelete) scripts as a companion utility. (You can search for the Internet to find various implementations .)
The myrm script is shown in listing 5.

Listing 5. Simple Utility used to back up a file before deleting it from the file system

#! /Bin/zsh
Backupdir = $ HOME/. tomb
Systemrm =/bin/rm
If [[-z $1 | $1 = "-- help"]
Then
Exec $ systemrm
Fi
If [[! -D $ backupdir]
Then
Mkdir-m 0700 $ backupdir | echo "$0: Cannot create $ backupdir"; exit
Fi
Args $ =$ (getopt dfiPRrvw $ *) | exec $ systemrm
Count = 0
Flags = ""
Foreach argument in $ args
Do
Case $ argument in
--) Break;
;;
*) Flags = "$ flags $ argument ";
(Count = $ count + 1 ));
;;
Esac
Done
Shift $ ($ count ))
For file
Do
[[-E $ file] | continue
Copyfile = $ backupdir/$ (basename $ file). $ (date "+ % m. % d. % y. % H. % M. % S ")
/Bin/cp-R $ file $ copyfile
Done
Exec $ systemrm $ = flags "$ @"


You should find that this Shell script is easy to understand, although there are some new content that has not been discussed before. Let's take a look at the new content and view the entire script.
When Shell runs a command (such as cp or ls), it generates a new process for the command and waits until the (sub) process is completed before it continues. The exec command also starts another command, but unlike the new process, exec uses a new command to "replace" the task of the current process, that is, the Shell process. In other words, exec re-uses the same process to start a new task. In the context of the script, exec immediately "terminates" the script and starts the specified task.
The unix utility getopt scans for location parameters to obtain the specified naming parameters. Here, dfiPRrvw lists-d,-f,-I,-P,-R,-r,-v, and-w. If other options are displayed, getopt fails. Otherwise, getopt returns an option string ending with a special string.
Shift command to delete the location parameter from left to right. For example, if the command behavior is myrm,-r-f-P file1 file2 file3, shift 3 deletes $0, $1, and $2, respectively, or-r,-f, and-P. File1, file2, and file3 will be re-numbered as $0, $1, and $2.
The case statement works in a similar way as the corresponding structure in traditional programming languages. It compares its parameters with each mode in the list. When a match is found, the corresponding code is executed. Similar to Shell, * matches all entries and can be used as the default action when no other matches are found.
The special symbol $ @ is expanded to all (other) location parameters.
Zsh operator $ = Split words at the blank boundary. $ = Is useful when you have a very long string and want to split it into parameters. For example, if the variable x contains the string '-r-F' -- this is a five-character word -- $ = x, it will become two separate words-r and-f.
After providing these explanations, you should be able to analyze the script in detail now. Next let's look at the code one by one:
The first part sets the variables used in the entire script.
The next block should be very familiar: It prints usage information when no parameter is provided. Why does it execute the (exec) Actual rm utility? If you name this script "rm" and place it in front of $ PATH, it can act as a replacement for/bin/rm. The error option of this script is also the/bin/rm error option, so this script allows/bin/rm to provide usage information.
The next block is created when the Backup Directory does not exist. If mkdir fails, the script is terminated and an appropriate error message is displayed.
The dash parameter in the parameter list of the next block location. If getopt is successful, $ args has an option list. If getopt fails, for example, when it cannot identify an option, it prints an error message and the script exits and displays usage information.
The subsequent block captures all the options in a string that are intended to be provided to rm. When the special getopt option -- is encountered, the option collection process is stopped. Shift deletes all processed parameters from the parameter list and retains the list of files and directories to be processed.
Copy each file and directory from a block starting with for file to save them in your own archive directory. The Directory of each file is copied to the archive directory by words (-R) with the current date and time as the suffix to ensure that the copy is unique, the entries with the same name in the previous archive will not be rewritten.
Finally, use the same command line option passed to the script to delete files and directories.
However, if you happen to need to delete it just now (accidentally delete ?) You can find the original copy in the archive.
March towards automation
The more time you use unix, the more likely you are to create scripts. Scripts can save time and effort for re-entering complex and long command sequences, and prevent errors. The Web is filled with useful scripts created by others for many purposes. Soon you will also release your own magic script.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.