Chapter 6 of linuxshell programming guide ------ control flow structure

Source: Internet
Author: User
Before writing the correct script, let's talk about the exit status. An exit status is returned when any command is running. If you want to observe the exit status, use the final status command: $ echo $? There are four major exit statuses. Two methods have been mentioned above, namely, the last command exit status $? And Control times before writing the correct script, let's talk about the exit status. An exit status is returned when any command is running. For example
If you want to observe the exit status, use the final status command:
$ Echo $?
There are four major exit statuses. Two methods have been mentioned above, namely, the last command exit status $? And control order commands ($,
| ). The other two types are processing the s h e l script or s h e l exit and corresponding exit status or function return code. Chapter 9 describes functions
Will also mention its return code.
To exit the current process, s h e l provides the command e x I t. the general format is:
Exit n
N is a number.
If you type e x I t at the command prompt only, if another s h e l is not created in the current state, the current s h e l is exited.
If you type e x I t in the script, s h e l will try (normally) to return the returned value of the previous command. There are many exit scripts
Value, but there are two most important types compared to scripts and general system commands:
Exit status 0: Exit successful, no error.
Exit status 1: Exit failed, and an error occurs somewhere.
You can add your exit status to the s h e l script (it will exit the script ). This is encouraged by the book because another
The s h e l script or the return function may need to extract the exit script from the s h e l script. In addition, I believe that the exit script is added to the script itself.
This value is a good programming habit.
If you want to, you can handle the error after a user input error, after a non-overwriting error, or after a normal processing.

Exit the script.

S h e l will provide a series of command declaration statements and other remedial measures to help you when the command is successful or fails, or need
Take the correct action when handling a command list.
These command statements are divided into two types:
Loop and flow control.

The I f, t h e n, and e l s e statements provide conditional tests. The test can be based on various conditions. For example, file permissions, length, and number
Value or string comparison. The returned values of these tests are either true (0) or false (1 ). Based on this result, you can
Related operations. Some test syntaxes have been involved in the conditional test.
The c a s e statement allows matching modes, words, or values. Once the mode or value matches, you can perform other operations based on this matching condition.
Statement.

Loop or jump refers to the repeated execution of a series of commands. This book mentions three types of loop statements:
Each time a for loop is processed, information in the list is displayed until the loop is exhausted.
Until loop this loop statement is not often used, u n t I l loop Until the condition is true. The condition part is at the end of the loop.
While loop w h I l e loop when the condition is true, the loop is executed, and the condition part is in the loop header.
Any loop of a flow control statement can be nested. for example, another f o r loop can be embedded in one f o r loop.
Now we will explain the loop and control flow, and use some script instances.


I f statement test condition. after the test condition returns true (0) or false (1), you can execute a series of statements accordingly. I f statement
Structure is very useful for error checks. The format is:
If condition 1
Then Command 1
Elif condition 2
Then Command 2
Else Command 3

F I
Let's explain the functions of the I f statement in detail.
If condition 1 If condition 1 is true
Then
Command 1 run Command 1
Elif condition 2 if condition 1 is not true
Then
Command 2 run Command 2
Else is not valid if condition 1, 2
Command 3: Execute command 3.
Fi complete
The I f statement must end with the word f I. Missing f I in I f statements is the most common error. I sometimes do the same.
E l I f and e l s e are optional. if there is no other part in the statement, e l I f and e l s e are not required. The I f statement can be
There are many e l I f parts. The most common I f statement is the if then fi structure.

The most common I f statement is:
I f condition
Then command
F I
When using the I f statement, the part t h e n must be placed in the new line; otherwise, an error occurs. If you do not want to branch, you must use
Delimiter. The rest of this book will take this form. Now the simple I f statement is changed:
If condition; t h e n
Command
F I

[Root @ localhost huangcd] # sh iftest2
Enter your name:
Your did not enter a information
[Root @ localhost huangcd] # cat iftest2
#! /Bin/bash
Echo-n "enter your name :"
Read NAME
If ["$ NAME" = ""]; then
Echo "your did not enter a information"
Fi

The following tests whether the file copy is normal. if the c p command does not copy the file m y f I l e to m y f I l e. B a k, an error is printed.
Incorrect information. Note that the script name is printed in 'basename $ 0' in the error message.
If the script exits due to an error, a good habit is to display the script name and direct it to a standard error. Users should know
The error script name is generated.

[Root @ localhost huangcd] # cat ifcp
#! /Bin/bash
If cp ok1.txt OK. bak; then
Echo "good copy"
Else
Echo "'basename $ 0': error cocould not copy the files"> & 2
Fi
[Root @ localhost huangcd] #./ifcp
Cp: stat failed ok1.txt ": no file or directory
Ifcp: error cocould not copy the files

2 indicates a standard error. if the file does not exist, if 2> & 1 is not added, the error message will be printed, enter the file. & 1 indicates that the standard output is directed to. This sentence is equivalent to cat cities> cities. copy 2> cities. copy or cat cities 1> cities. copy 2> cities. copy or cat cities 2> cities. copy 1> & 20: standard input, 1: standard output, 2: Standard error

When running some management scripts, you may need to run them in the root directory, especially by moving a global file or granting permissions.
Limited to change. A simple test can be used to check whether the program is running in the root directory. The following script uses the variable d I R E C TO RY.
The command replacement operation of the current directory, and then the variable value is compared with the "/" string (/is the root directory ). If the variable value and character
The user exits the script, and the exit status is 1, which means the error message is generated.

[Root @ localhost huangcd] #./ifpwd
You need to be in the root directory. not/home/huangcd
[Root @ localhost huangcd] # cat ifpwd
#! /Bin/bash
DIRCTORY = 'pwd'
If ["$ DIRCTORY "! = "/"]
Then echo "you need to be in the root directory. not $ DIRCTORY"> & 2
Exit 1
Fi

The I f statement can be used to test the number of parameters in the input script. Use the specified variable $ # to indicate the number of called parameters. Yes
Check whether the number of required parameters is equal to the number of called parameters.
The following test ensures that the script has three parameters. If no, a standard error is returned, and the code
Exit and the exit status is displayed. If the number of parameters is 3, all parameters are displayed.

[Root @ localhost huangcd] # cat ifpatam
#! /Bin/bash
If [$ #-lt 3]
Then echo "Usage: 'basename $ 0' arg1 arg2 arg3"> & 2
Exit 1
Fi
Echo "arg1: $1"
Echo "arg2: $2"
Echo "arg3: $3"
[Root @ localhost huangcd] #./ifpatam cup medal
Usage: ifpatam arg1 arg2 arg3
[Root @ localhost huangcd] #./ifpatam cup medal thophy
Arg1: cup
Arg2: medal
Arg3: thophy

The following example tests whether the environment variable e d I TO R has been set. If the variable e d I TO R is empty, this information will be notified
User. If the editing type is set, the editing type is displayed on the screen.

[Root @ localhost huangcd] # cat ifeditor
#! /Bin/bash
If [-z $ EDITORS]
Then echo "your EDITOR environment is not set"
Else
Echo "Using $ EDITOR as the fefault editor"
Fi
[Root @ localhost huangcd] #./ifeditor
./Ifeditor: line 2: [-z: command not found
Using as the fefault editor

You can pass the location parameter to the script and test the variable. Here, if you enter the directory name after the script name,
The script resets the $1 special variable to a more meaningful name. That is, d I R E C TO RY. Check whether the directory is empty, as shown in figure
If the directory is empty, ls-A returns null, and then returns A message.

[Root @ localhost huangcd] # sh ifdirec
Is indeed empty
[Root @ localhost huangcd] # sh ifdirec/home
/Home is indeed empty
[Root @ localhost huangcd] # cat ifdirec
#! /Bin/bash
DIRECTORY = $1
If ["'ls-A $ directory'" = ""]
Then echo "$ DIRECTORY is indeed empty"
Else
Echo "$ DIRECTORY is not empty"
Fi

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.