Shell programming (2)

Source: Internet
Author: User
Shortcut Operators

If you are familiar with the C language, you may like the following expressions:

[-F "/etc/shadow"] & echo "This computer uses shadow passwors"

Here & is a shortcut operator. If the expression on the left is true, execute the Statement on the right. You can also think of it as a logical operation. In the above example, if the/etc/shadow file exists, print "This computer uses shadow passwors ". Similarly, operations (|) are 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

The script first checks whether mailfolder is readable. If it is readable, the "From" line in the file is printed. If it is not readable or the operation takes effect, print the error message and exit the script. There is a problem here, that is, we must have two commands:

-Print the error message.

-Exit the program.

We use curly braces to put the two commands together as one command in the form of an anonymous function. General functions will be mentioned below.

We can use the if expression to do anything without the sum or operator, but it is much more convenient to use the sum or operator.

A case expression can be used to match a given string, not a number.

Case... in
...) Do something here ;;
Esac

Let's look at an example. The file command can identify the file type of a given file, for example:

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 named smartzip, which can automatically decompress bzip2, gzip, and zip compressed files:

#! /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. The variable contains the first parameter value passed to the program. That is, when we run:

Smartzip articles.zip
$1 is the string articles.zip

The select expression is a bash extension application, especially for interactive use. You can select from a group of different values.

Select var in...; do
Break
Done
... Now $ VaR can be used ....
The following is an example:
#! /Bin/sh
Echo "What is your favorite OS? "
Select VaR in "Linux" "GNU Hurd" "Free BSD" "other"; do
Break
Done
Echo "you have selected $ Var"

The following is the result of running the script:

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 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. The keyword "break" is used to jump out of the loop. The keyword "continue" is used to directly jump to the next loop without executing the remaining part.

The for-loop expression is used to view a string list (strings are separated by spaces) and then assigned to a variable:

For VaR in...; do
....
Done

In the following example, ABC is printed to the screen:

#! /Bin/sh
For var in a B C; do
Echo "var is $ var"
Done

The following is a more useful script showrpm. Its function is to print 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"]; then
Echo "=====================$ rpmpackage ===================="
Rpm-qi-p $ rpmpackage
Else
Echo "ERROR: cannot read file $ rpmpackage"
Fi
Done

The second special variable $ * is displayed, which contains all input command line parameter values. If you run showrpm openssh. rpm w3m. rpm webgrep. rpm

$ * Contains three strings: openssh. rpm, w3m. rpm, and webgrep. rpm.

Quotation marks

Before passing any parameters to a program, the program extends the wildcards and variables. Here, the extension means that the program will replace the wildcard (for example, *) with the appropriate file name, and replace the variable with the variable value. To prevent such replacement, you can use quotation marks: Let's take a look at an example. Suppose there are some files in the current directory, two JPG files, mail.jpg and tux.jpg.

#! /Bin/sh
Echo *. jpg

This will print the result of "mail.jpg tux.jpg.

Quotation marks (single quotation marks and double quotation marks) will prevent such wildcard extension:

#! /Bin/sh
Echo "*. jpg"
Echo '*. jpg'

This will print "*. jpg" twice.

Single quotes are stricter. It can prevent any variable extension. Double quotation marks can prevent wildcard extension but allow variable extension.

#! /Bin/sh
Echo $ Shell
Echo "$ shell"
Echo '$ shell'

The running result is:

/Bin/bash
/Bin/bash
$ Shell

Finally, there is also a method to prevent this extension, that is, to use the Escape Character -- reverse oblique ROD:

Echo *. jpg
Echo $ Shell

This will output:

*. Jpg
$ Shell
Here documents

To pass several lines of text to a command, here documents is a good method. It is very useful to write a helpful text for each script. If we have the here documents, we do not need to use the echo function to output a row. A "Here document" starts with <, followed by a string, which must also appear at the end of the here document. The following is an example. In this example, we rename multiple files and print the help using here documents:

#! /Bin/sh
# We have less than 3 arguments. Print the help text:
If [$ #-lt 3]; then
Cat <ren -- renames a number of files using sed regular expressions

USAGE: ren 'regexp' 'replace '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
# 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's discuss it in detail. The first if expression determines whether the number of input command line parameters is smaller than 3 (special variable $ # indicates the number of parameters included ). If the number of input parameters is less than three, the help text is passed to the cat command and then printed on the screen by the cat command. Print the help text and exit the program. If the input parameter is equal to or greater than three, we assign the first parameter to the variable OLD, and the second parameter to the variable NEW. Next, we use the shift command to delete the first and second parameters from the parameter list, so that the original third parameter becomes the first parameter in the parameter list $. Then we start the loop. The command line parameter list is assigned to the variable $ file one by one. Then we determine whether the file exists. If yes, we use the sed command to search for and replace the file to generate a new file name. Then, assign the command result in the backslash to newfile. In this way, we can achieve our goal: Get the old and new file names. Use the mv command to rename the file.

Function

If you write a slightly more complex program, you will find that the same code may be used in several places in the program, and you will also find that if we use a function, it is much more convenient. A function looks like this:

Functionname ()
{
# Inside the body $1 is the first argument given to the function
#$2 the second...
Body
}

You must declare the function at the beginning of each program.

The following is a script named xtitlebar. You can use this script to change the name of the terminal window. Here we use a function called help. As you can see, this defined function is used twice.

#! /Bin/sh
# Vim: set sw = 4 ts = 4 et:

Help ()
{
Cat <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"
#

It is a good programming habit to help other users (and you) use and understand scripts.

Command Line Parameters

We have seen Special variables such as $ * and $1, $2... $9. These special variables include the parameters you input from the command line. So far, we have only learned some simple command line syntax (such as some mandatory parameters and the-h option for viewing help ). However, when writing more complex programs, you may find that you need more custom options. The common practice is to add a minus sign before all optional parameters, followed by a parameter value (such as a file name ).

There are many ways to analyze input parameters, but the following example using the case expression is a good method.

#! /Bin/sh
Help ()
{
Cat <This is a generic command line parser demo.
Usage example: extends parser-l hello-f ---somefile1 somefile2
HELP
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 the script as follows:

Extends parser-l hello-f ---somefile1 somefile2

The returned 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 first loops through all input command line parameters and compares the input parameters with the case expression. If the input parameters match, a variable is set and the parameter is removed. According to the Convention of the unix system, the first input should be the parameter containing the minus sign.
 

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.