Quick operator
Friends who are familiar with C language may like the following expressions:
[-f "/ etc / shadow" && echo "this Computer Uses Shadow PassWors"
Here && is a shortcut, if the expression on the left is true, perform 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 the 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 the program
We put two commands together as a command as a command in the form of anonymous function as an anonymous function. 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
Let us look at an example. File commands can identify file types of a given file, such as:
File Lf.gz
This 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 that automatically extracts the compressed file of BZIP2, Gzip, and Zip types:
#! / bin / sh
ftype = `file" $ 1 "`
Case "$ ftype" in
"$ 1: zip archive" *)
Unzip "$ 1" ;;
"$ 1: gzip commitsed" *)
Gunzip "$ 1" ;;
"$ 1: bzip2 commitsed" *)
Bunzip2 "$ 1" ;;
*) Error "File $ 1 can not be uncompressed with smartzip" ;;
ESAC
You may notice that we use a special variable with $ 1 here. This variable contains the first parameter value passed to the program. That is, when we run:
Smartzip Articles.zip
$ 1 is 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 ....
Below is an example:
#! / bin / sh
echo "What is your favorite os?"
Select Var in "Linux" "GNU Hurd" "Free BSD" "Other"; Dobreak
DONE
Echo "You Have SELECTED $ VAR"
Here 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 expression View a string list (string space separated) and assign it to a variable:
For var in ....; do
....
DONE
In the following example, the ABC to the screen will be printed separately:
#! / bin / sh
For VAR in A B C; DO
Echo "VAR IS $ VAR"
DONE
Here is a more useful script showrpm, which is the statistics of 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"];.
echo "=============== $ rpmpackage ========================================
RPM -QI -P $ rpmpmpackage
Else
Echo "Error: Cannot Read file $ rpmpackage"
Fi
DONE
The second special variable is there thereon, which contains all input command line parameter values. If you run ShowrPM OpenSSH.RPM W3M.rpm WebGrep.rpm
At this point $ * contains 3 strings, ie openssh.rpm, w3m.rpm and webgrep.rpm.
quotation marks
The program expands wildcards and variables before passing any parameters to the program. 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 dual 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'
The result of the operation is:
/ BIN / BASH
/ BIN / BASH
$ Shell
Finally, there is also a way to prevent this extension, that is, use escape characters - anti-screw rod:
echo * .jpg
Echo $ shell
This will output:
* .jpg
$ Shell
Here Documents
When you want to pass a few lines to a command, Here Documents (Translator Note: There is currently no way to translate the word) a good method. It is useful to write a part of the helpibility for each script. At this time, if we have the four Here Documents, you don't have to use the Echo function to output a row of rows. A "here document" with << starts, after connecting a string, this string must also appear at the end of the Here Document. Here is an example in which we rename multiple files and use Here Documents to print help:
#! / bin / sh
# We Have Less Than 3 Arguments. Print The Help Text:
IF [$ # -lt 3];.
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"]; then
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 whether the input command line argument is less than 3 (special variable $ # means 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 3, we assign the first parameter to the variable OLD, and 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. function
If you have written some slightly complex programs, you will find the same code in several places in a few places, and you will find that if we use a function, it will be much more 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 the beginning of 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"
#
Providing help in scripts is a good programming habit, so that other users (and you) use and understand scripts.
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 commnd line parser demo.
USAGE EXAMPLE: CMDPARSER -L HELLO -F ---SOMEFILE1 Somefile2help
EXIT 0
}
While [-n "$ 1"]; do
Case $ 1 in
-H) Help; shift 1 ;; # function help is called
-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 like this:
cmdparser -l hello -f - -somefile1 somefile2
The result of returning is:
OPT_F IS 1
OPT_L IS Hello
First arg is -somefile1
2nd arg is somefile2
How is 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.