How to write a shell script

xiaoxiao2021-03-05  32

How to write a shell script This article combines a lot of instances to describe how to write a shell script. Why do shell programming in a Linux system, although there are a variety of graphical interface tools, Sell is still a very flexible tool. Shell is not only a collection of commands, but also a great programming language. You can use shell to automate a large number of tasks, Shell is particularly good at system management tasks, especially for more important tasks that are more important, maintainability, and portability. Below, let's take a look at how shell works: Building a script Linux has a lot of different shells, but usually we use Bash (Bash Again Shell) for shell programming, because Bash is free and easy to use. So the scripts provided in this article are bash (but in most cases, these scripts can also run in Bash's big sister, Bourne Shell). Like other languages, we use any of the text editor, such as Nedit, Kedit, Emacs, VI, etc. to write our shell programs. The program must start with the following row (must be in the first line of the file): #! / Bin / sh symbol #! Used to tell the system that the parameters behind it are used to execute the file. In this example we use / bin / sh to execute the program. When editing the script, if you want to execute this script, you must also make it executable. To make the script execut: chmod x filename then, you can perform your script by entering: ./filename. Note When the SHELL programming is performed, the sentence indicates the sentence until the end of this line. We sincerely recommend that you use comments in the program. If you use a comment, even if you don't use this script, you can understand the role and working principle of this script in a short period of time. Variables You must use variables in other programming languages. In the shell program, all variables are composed of strings and you do not need to declare variables. To assign a value, you can write this: Variable name = value to remove the variable value to add a dollar sign ($) in front of the variable: #! / Bin / sh # Assignment value: a = "Hello World" # Now print The contents of the variable A: echo "a is:" Echo $ A Enter the above in your editor, then save it as a file first. After the CHMOD X first is executed, it can be executed, and finally input ./first executes the script. This script will output: a is: Hello World Sometimes it is easy to confuse with other texts, such as: Num = 2 echo "this is the $ numnd" This does not print "this is the 2nd", but only Print "this is the" because the shell will go to search the variable NumND value, but there is no value when this variable is. You can use the curly brackets to tell Shell. We want to print Num variables: Num = 2 echo "this is the $ {NUM} nd" This will print: this is the 2nd has a number of variables are automatically set, this will be Discussions are discussed when these variables are used later.

If you need to process mathematical expressions, you need to use programs such as EXPR (see below). In addition to the general SHELL variables only in the program, there are environment variables. Variables processed by the export keyword are called environment variables. We don't discuss environment variables because usually use environment variables only in the login script. Shell Commands and Process Control You can use three types of commands in the shell script: 1) UNIX command: Although any UNIX command can be used in the shell script, it is still a relatively more common command. These commands are usually used for files and text operations. Commonly used command syntax and function Echo "some text": Print text content on the screen LS: File list wc -l filewc -w filewc -c file &: calculate the number of words in the calculation file in the calculation file in the calculation file SourceFile Destfile &: File Copy MV OldName NEWNAME: Rename File or Mobile File RM File &: Delete File Grep 'Pattern' File &: Search Strings in the File, such as: Grep 'SearchString' file.txt cut -b colnum file &: specifies to display The file content range, and output them to standard output devices such as: Output Each line of the 5th to nine characters CUT -B5-9 file.txt must not be confused with the CAT command, this is two completely different commands CAT file.txt: Output file content to the standard output device (screen) File Somefile &: Get file type read var: prompt user input, and give the input assignment to the variable sort file.txt: Sort the line in the file.txt file UNIQ: Deleting the ranks of the text file, such as: sort file.txt | UNIQ EXPR: Mathematical operations EXAMPLE: Add 2 and 3EXPR 2 " " 3 Find: Search files such as: Search Find. -name filename -print TEE: Output data to standard output devices (screens) and files such as: SomeCommand | Tee Outfile Basename File &: Returns a file name that does not contain the path, such as: baseName / Bin / Tux will return Tux DirName File &: Return to files, such as: DIRNAME / bin / tux will return / bin head file &: Print text files a few lines of tail file: Print text files Several lines of SED: SED is a basic lookup replacement. You can read text from standard inputs (such as command pipes), and output the result to the standard output (screen). This command is searched using a regular expression (see). Don't confuse the wildcards in the shell. For example: replace LinuxFocus with LinuxFocus: cat text.file | SED '> NewText.File awk: awk to extract fields from text files. By default, the field split is a space, you can use -f to specify other splites. Cat file.txt | awk -f, '{print $ 1, "$ 3}" We use, as a field split, and print one and the third field.

If the contents are as follows: Adam Bor, 34, Indiakerry Miller, 22, USA command output is: Adam Bor, Indiakerry Miller, USA 2) Concept: pipe, redirection, and backtick These are not system commands, but they are really important . The pipe (|) uses the output of a command as the input of another command. GREP "Hello" file.txt | wc -l Search in file.txt and contains a row with "Hello" and calculates the number of rows. The output of the grep command here as the input of the WC command. Of course you can use multiple commands. Redirection: Output the result of the command to the file instead of the standard output (screen). > Write files and override the old file >> Add to the end of the file, keep the old file content. Reverse shorting of slashes Use the short-shot slash to output an order of the output as a command line parameter of another command. Command: find. -Mtime -1 -type f -print Used to find files that have been modified within the last 24 hours (-mtime -2 indicating the past 48 hours). If you want to make all the finded files a package, you can use the following scripts: #! / Bin / sh # the ticks are backticks (`) NOT NORMAL quotes ('): tar -zcvf lastmod.tar.gz` find . -Mtime -1 -type f -print` 3) Process Control "IF" expression If the condition is true, the part is executed behind: if ....; the .... Elif ....; ... Else .... Fi Most of the cases, you can use the test command to test the condition. For example, you can compare the string, determine if the file exists and whether it is readable, and so on ... usually use "[]" to represent the condition test. Note that the space here is important. To ensure the space of square brackets. [-F "somefile"]: Judging whether it is a file [-x "/ bin / ls"]: Judgment / bin / LS exists and has executable permissions [-n "$ var"]: Determine if the $ VAR variable is Value ["$ a" = "$ b"]: Judging whether $ A and $ B are equal to the MAN Test to view all test expressions to compare and judgment types. Perform the following scripts directly: #! / Bin / sh if ["$ shell" = "/ bin / bash"]; the echo "Your login shell is the bash (bourne again shell" else echo "Your Login Shell Is Not Bash But $ shell "Fi Variable $ shell contains the name of the login shell, we compare it with / bin / bash. Shortcut Operators are familiar with C language friends may like the following expression: [-f "/ etc / shadow"] && echo "this computer buy shadow passwors" here && is a shortcut, if the expression on the left is True is the statement on the right. You can also think that it is a logical operation.

In the above example, if the / etc / shadow file exists, "this Computer Uses Shadow PassWors" is printed. Also or operate (||) is also available in shell programming. Here is an example: #! / Bin / sh mailfolder = / var / spool / mail / james [-r "$ mailfolder"] '' {echo "Can not read $ mailfolder" EXIT 1;} echo "$ mailfolder Has Mail From: "GREP" ^ from "$ mailfolder This script first determines whether MailFolder is readable. If readable, print "from" one line in the file. If you do not read or operate, the script exits after the error message is printed. There is a problem here, that is, we must have two commands: - Print Error Message - Exit User We use the curb brackets to put two commands together as an anonymous function as a command. The general function will be mentioned below. Don't use and or operate, we can also use IF expressions, but use or operators will be more convenient. The CASE expression can be used to match a given string instead of a number. Case ... in ...) Do Something Here Esac lets us see an example. File commands can distinguish a file type of a given file, such as File Lf.gz will return: lf.gz: gzip compressed data, deflated, Original FileName, Last Modified: Mon Aug 27 23:09:18 2001, OS : UNIX We use this to write a script called Smartzip, which can automatically extract the compressed files for BZIP2, Gzip, and Zip types: #! / Bin / sh ftype = `file" $ 1 "` case "$ ftype" in " $ 1: zip archive "*) Unzip" $ 1 "$ 1: gzip compressed" *) Gunzip "$ 1" "$ 1: bzip2 compressed" *) Bunzip2 "$ 1" *) Error "File $ 1 can not be uncompressed with smartzip" ;; Esac You may notice that we use a special variable $ 1 here. This variable contains the first parameter value passed to the program. That is, when we run: Smartzip Articles.zip $ 1 is a string Articles.zip SELECT expression is an extension application of Bash, especially in interactive use. Users can choose from a set of different values.

SELECT VAR IN ... DO BREAK DONE .... NOW $ VAR CAN BE USED .... GNU Hurd "" Free BSD "" Other "; Do Break Done Echo" You Have SELECTED $ VAR "below is the result of this script run: What is your favorite OS? 1) Linux 2) Gnu Hurd 3) Free BSD 4) Other #? 1 You Have Selected Linux You can also use the following loop expression in the shell: While ...; do .... done while-loop will run until the expression test is true. Will Run While The Expression That We Test for Is True. Keyword "BREAK" is used to jump out of the loop. The keyword "continue" is used to directly skip to the next loop directly. For-loop expressions see a string list (string space separated) and then assign it to a variable: for var in ....; do .... DONE in the example below, will print ABC to On the screen: #! / Bin / sh for var in a b c do echo "VAR IS $ VAR" DONE Bell below is a more useful script showrpm, its function is to print some RPM packages: #! / Bin / SH # list a content summary of a number of rpm packages # usage: showrpm rpmfile1 rpmfile2 ... # example: showrpm / cdrom/redhat/rpms/*.rpm for rpmpackage in $ *; do if [-r "$ rpmpackage" ]; then "=============== $ rpmpackage ==============" rpm -qi -p $ rpmpackage else echo "error: Cannot Read file $ rpmpackage "Fi Done" The second special variable has a second special variable contains all input command line parameter values. If you run showrpm openssh.rpm w3m.rpm webgrep.rpm, $ * contains 3 strings, ie openssh.rpm, w3m.rpm and webGrep.rpm. Quotation marks extend wildcard before passing any parameters to programs. And variables. The so-called extension here is that the program will replace the wildcard (such as *) to the appropriate file name, and its variable replaces a variable value. In order to prevent this replacement, you can use quotation marks: Let's take an example, assume some files, two JPG files, mail.jpg, and tux.jpg in the current directory. #! / Bin / sh echo * .jpg This will print the result of "mail.jpg tux.jpg".

Quotation marks (single quotes and double quotes) will prevent this wildcard extension: #! / Bin / sh echo "* .jpg" echo '* .jpg' This will print "* .jpg" twice. Single quotes are more stringent. It prevents any variable extensions. Dual quotes can prevent wildcards from expand but allow variables to expand. #! / bin / sh echo $ shell echo "$ shell" echo '$ shell' Run results are: / bin / bash / bin / bash $ shell Finally, there is also a way to prevent this extension, that is, use escape Character - Anti-Scrope: Echo * .jpg Echo $ shell This will output: * .jpg $ shell here, when you want to pass a few lines of text to a command, Here Document. (Translator Note: I haven't seen it yet It is a good method for a suitable translation of the term. It is useful to write a helpful text to each script. At this time, if we have four Here Document. If you don't have to use the Echo function to output. A "Here Document.quot; with the beginning of the <<, then connect the last string, this string must also appear in Here Document. Last. Below is an example, in this example, we rename multiple files, And use Here Document. Print Help: #! / Bin / sh # We Have Less Than 3 Arguments. Print The Help Text: IF [$ # -lt 3] Then Cat << Help Ren - Renames a Number of Files Using SED Regular Expressions Usage: Ren 'Regexp' 'Replacement' Files ... EXAMPLE: RENAME All * .htm files in * .html: Ren 'htm $' 'html' * .htm Help Exit 0 Fi Old = "$ 1" new = "$ 2" # The Shift Command Removes One Argument from The List of # Command Line Arguments. Shift Shift # $ * Contains now all the files: for file in $ *; do if [-f "$ file"] Then newfile = ` Echo "$ file" | SED "S / $ {old} / $ {new} / g" `IF [-f" $ newfile "]; the echo" Error: $ newfile exists already "else echo" Renaming $ File To $ newfile ... "MV" $ file "" $ newfile "FI FI DONE This is a complex example. Let us discuss in detail. The first IF expression determines if the input command line parameter is less than 3 (special variable $ # Indicates a number of parameters). If the input parameter is less than 3, the help text is passed to the CAT command, and then print it on the screen by the CAT command. Print help text post-programs exit. If the input parameter is equal to or greater than Three, we assign the first parameter to the variable OLD, the second parameter assigns the variable New.

Next, we use the shift command to remove the first and second parameters from the parameter list, so the original third parameter is the first parameter of the parameter list *. Then we start loop, the command line parameter list is assigned to the Variable $ File by one. Then we determine if the file exists, if there is, search and replace the new file name via the SED command search. Then, the result of the insection of the inside the slash is then assigned to newfile. This way we have achieved our goal: got old file name and new file name. Then use the mv command to rename it. Functions If you write some slightly complex programs, you will find that you may use the same code in several places, and you will find that if we use functions, it is convenient. A function is this look: functionname () {# inside the body $ 1 is The first argument given to the function # $ 2 The second ... body} You need to declare the function in each program. Below is a script called Xtitlebar, you can change the name of the terminal window using this script. A function called Help is used here. As you can see, this definition function is used twice. #! / bin / sh # Vim: set sw = 4 Ts = 4 et: help () {cat << Help Xtitlebar - Change the name of an xterm, gnome-terminal or kde konsole usage: Xtitlebar [-h] " String_for_titelbar "Options: -h Help Text Example: Xtitlebar" CVS "Help EXIT 0} # in case of error or if --h is given we call the function help: [-z" $ 1 "] && help [" $ 1 "=" -H "] && help # send the escape sequence to change the xterm Titelbar: Echo -e" 33] 0; $ 107 "# in the script is a good programming habit, so that other users (and you) Use and understand the script. Command line parameters We have seen $ * and $ 1, $ 2 ... $ 9 and other special variables, including the parameters input from the command line from the command line. So far, we only understand some simple command line syntax (such as some mandatory parameters and viewing the -h option). But when writing more complex programs, you may find more custom options. The usual convention is to add a minus sign before all optional parameters, and then add the parameter values ​​(such as file name). There is a lot of ways to achieve analysis of input parameters, but the following examples use case expressions are a nice way.

#! / bin / sh help () {cat << Help this is a generic command line parser demo. usage example: cmdparser -l hello -f - -somefile1 somefile2 help exit 0} while [-n "$ 1"; Do Case $ 1 in -H) Help; Shift 1 ;; # function help is caled -f) OPT_F = 1; Shift 1 ;; # variable opt_f is set -l OPT_L = $ 2; shift 2 ;; # -l takes an Argument -> Shift by 2 -) Shift; Break ;; # end of options - *) Echo "Error: No Such Option $ 1. -h for help"; exit 1 ;; *) Break ;; esac done echo "OPT_F IS $ OPT_F "echo" OPT_L IS $ OPT_L "Echo" First Arg IS $ 1 "Echo" 2nd Arg IS $ 2 "You can run this script: cmdparser -l hello -f - -somefile1 SomeFile2 The result is: OPT_F IS 1 OPT_L IS HELLO FIRST ARG IS --SOMEFILE1 2nd arg is somefile2 How does this script work? The script is first compared in all input command line parameters, comparing the input parameters to the CASE expression, set a variable if the match is matched and the parameter is removed. According to UNIX systems, the first input should be a parameter containing minus. Example General Programming Steps Now let's discuss the general steps to write a script. Any excellent script should have help and input parameters. And write a fake script (framework.sh), which contains the framework structure that most scripts need, is a very good idea. At this time, we only need to execute the copy command when writing a new script: CP framework.sh myScript and then insert your own function. Let's look at two examples: binary to decimal conversion script B2D converts the binary number (such as 1101) into the corresponding decimal number.

This is also an example of mathematics operation with the expr command: #! / Bin / sh # Vim: set sw = 4 TS = 4 et: help () {cat << Help B2H - Convert binary to decimal usage: b2h [ H] binarynum options: -h Help text Example: B2H 111010 Will Return 58 Help Exit 0} Error () {# Print An Error and Exit Echo "$ 1" EXIT 1} lastchar () {# Return The Last Character of A String in $ RVAL IF [-z "$ 1"]; then # Empty string rval = "" Return Fi # wc Puts Some Space Behind the Output this is why we need Sed: Numofchar = `echo -n" $ 1 "| WC -C | Sed 's / // g' `# Now cut out the last char rval =` echo -n "$ 1" | cut -b $ number} chop () {# Remove The Last Character in String and Return It in $ RAL IF [-z "$ 1"]; then # Empty string rval = "" Return Fi # wc Puts Some Space Behind The Output this is why we need SED: Numofchar = `echo -n" $ 1 "| wc -c | sed ' S / / / g '`IF [" $ numofchar "=" 1 "]; then #Ons one char in string rval =" "Return Fi Numofcharminus1 =` expr $ Numofchar "-" 1` # Now cut All but the last char: rval = `echo -n" $ 1 "| cut -b 0 - $ {numofcharminus1}`} while [-n "$ 1"]; do case $ 1 in -h) Help; shift 1 ;; # Function Help is Called -) Shift; Break ;; # end of options - *) Error "Error: No Such Option $ 1. -h for help" ;; *) Break ;; esac done # the main program sum = 0 weight = 1 # One Arg Must Be Given: [-z "$ 1"] && Help binnum = "$ 1" binnumorig = "$ 1" while [-n "$ binnum"]; do lastchar "$ binnum" f ["$ rval"

= "1"]; THEN SUM = `EXPR" $ weight "" "" $ su "` Fi # Remove The Last Position in $ Binnum Chop "$ binnum" binnum = "$ =` = `expr" $ weight "*" 2` Done Echo "Binary $ BINNUMORIG IS DECIMAL $ SUM" # This script uses the algorithm used by decimal and binary weight (1, 2, 4, 8, 16, ..), such as binary "10 "It can be converted into Ten Because: 0 * 1 1 * 2 = 2 In order to get a single binary number, we use the lastchar function. This function uses the WC-C calculating the number of characters and then uses the CUT command to take out a character. The function of the CHOP function is to remove the last character. File loop programs may be a member you want to save all messages into people in a file, but after a few months, this file may become great to make access to the file. Slow down. The following script RotateFile can solve this problem.

转载请注明原文地址:https://www.9cbs.com/read-33474.html

New Post(0)