Shell programming (2)

Source: Internet
Author: User
Tags uppercase letter
The most important script language in Linux is Bash. I will write this (I will only use this :)). Compared with other development languages (such as C), bash is a relatively simple language, mainly used to write some script code, some batch processing or installation programs. You can check that there are many script files in the/etc/init. d/directory to control various services.

First look at a "Hello world !" Example:
Create a new file named hello. Sh in a directory and run the following code:

#! /Bin/sh
Echo "Hello world! "

Okay. That's all. Save, enter the directory for saving "Hello. Sh" at the command prompt, and execute:

# Sh hello. Sh (Press ENTER)
See it? Haha, but you should be glad not to be too early, just don't explain anything, just like the "Hello world. "the same, it is far from the master.

Let's take a look at the use of variables in the bash script.
Modify "Hello world !" The example is changed to the following:

#! /Bin/bash
# This is a very simple example
STR = "Hello world! "
Echo $ Str

Save and execute the script as shown in the preceding method. You will see the same effect as before. Let's take a look at the meaning of each sentence:
The first line ,#! It indicates the type of the file hello. Sh, which is similar to the file Suffix in Windows to indicate different file types. For Linux "#! "And the information after the string determine the file type. In bash, the first line "#! "And later"/bin/bash "indicates that the file is a bash program and must be interpreted and executed by the bash program in the/bin directory. Bash is usually stored in the/bin directory. This line is fixed.
In the second line, "# This is a..." is the comment of the bash program. In the bash program, The beginning and end of the line are considered as program comments, which is equivalent to "//" in C/C ++.
The third line is to assign a value to a variable named Str.
The function of the ECHO statement in the fourth line is to output the string or variable content after Echo to the standard output. Note that most statements in bash do not end with semicolons.

For the third row, someone may ask: in C/C ++, all variables belong to a certain type. What is the type of str? In bash, variable definitions are not required. There is no definition process like "int I. If you want to use a variable, it can be used directly as long as it has not been previously defined. Of course, the first statement you use this variable should assign an initial value to him, if you do not assign an initial value, it is not related, but the variable is null (Note: It is null, not 0 ).

Note the following when using variables:
1. When a variable is assigned a value, no space is allowed between the left and right sides of "=;
2. The end of a bash statement does not require a semicolon (";");
3. Except for variable assignment and in the for loop statement header, the variable in Bash must be preceded by the "$" symbol.

In more detailed bash documents, it is stipulated that variables should be used in the form of $ {STR}. If your script has an inexplicable error, check whether this problem is caused.

Since the variables in bash do not need to be defined, there is no type. Can a variable store both integers and strings? Yes!
A variable can be defined as a string or an integer. If an integer operation is performed on the variable, it is interpreted as an integer. If a string operation is performed on the variable, it is viewed as a string. See the following example:

#! /Bin/bash
X = 2006
Let "x = $ x + 1"
Echo $ x
X = "a string ."
Echo $ x

Run the following command?

A New Keyword: Let appears. There are several types of integer variable calculation: "+-*/%", which means the same as the word surface. A backslash must be added before * And, it has been prevented from being explained by shell first. Integer operations are generally implemented through the let and expr commands. For example, you can write the variable X by adding 1: let "x = $ x + 1" or X = 'expr $ x + 1'

For runtime parameters, we sometimes want to input parameters when executing the script, such as: # sh mysh. sh HDZ (Press ENTER). It is very simple. In bash, the "$" symbol should also be added before the variables passed in.

$ # Number of command line parameters for the input script;

$ * All command line parameter values, with spaces between each parameter value;

Location variable

$0 command itself (shell file name)

$1 The first command line parameter;

$2 the second command line parameter;

...

OK. Edit the following script:
#! /Bin/sh

Echo "Number of vars:" $ #

Echo "values of vars:" $ *

Echo "value of var1:" $1
Echo "value of var2:" $2
Echo "value of var3:" $3
Echo "value of var4:" $4

Save the file name as my. Sh, and input the following parameter during execution: # sh my. Sh a B c d e (Press ENTER). Then you can see the result to better understand the meaning of each variable. If the accessed parameter is not passed in during execution, such code:
Echo & quot; Value of var4: & quot; $100

If no 100 parameters are input during execution, the obtained value is null.

If a variable is used in a bash program, the variable remains valid until the end of the program. To make a variable exist in a local program block, the concept of local variables is introduced. In bash, a local variable can be declared by adding the local keyword when the variable is assigned the initial value for the first time, as shown in the following example:

#! /Bin/bash
Hello = "var1"
Echo $ hello
Function Hello {
Local Hello = "var2"
Echo $ hello
}

Echo $ hello

The execution result of this program is:

Var1
Var2
Var1

The execution result indicates that the value of the global variable $ hello is not changed when the function hello is executed. That is to say, the effect of the local variable $ Hello only exists in the function block.

Differences between bash variables and C Variables
Here, programmers who are not familiar with Bash programming but are very familiar with the C language summarize the issues that need to be paid attention to when using variables in the bash environment.

1. When referencing a variable in Bash, you must add the "$" symbol before the variable (the first value assignment and the "$" symbol is not required in the for loop header );
2. There is no floating point operation in bash, so there is no variable of the floating point type available;
3. The comparison symbols of Integer Variables in bash are completely different from those in C language, and the arithmetic operations of integer variables must also be processed by let or expr statements;

Next let's take a look at the comparison between variables:
In comparison, the integer and string variables are different. For details, see the following table:

Corresponding operation Integer Operation string operation
Same-eq =
Different-ne! =
Greater than-GT>
Less than-lt <
Greater than or equal to-Ge
Less than or equal to-le
Blank-z
Not empty-n

For example:
If the integers A and B are equal, write if [$ A = $ B].
To determine whether integer A is greater than integer B, write if [$ A-GT $ B].
Compare whether the strings A and B are equal to write: If [$ A = $ B]
To judge whether string a is null, write: If [-Z $ A]
To determine whether integer A is greater than B, write: If [$ A-GT $ B]

Note: There are spaces on the left and right sides of the "[" and "]" symbols.

Bash is the shell of the Linux operating system. Therefore, the system file must be an important object to be operated by bash.
OPERATOR:

Meaning (true is returned if the following requirements are met)

-E file already exists
-F files are common files.
-S file size is not zero
-D file is a directory
-The R file can be read by the current user.
-W files can be written to the current user
-The X file can be executed on the current user.
-The GID flag of the G file is set.
-Ufile uid flag is set
-O files belong to the current user
The Group ID of the-G file is the same as that of the current user.
File1-nt file2 file file1 is updated than file2
File1-ot file2 file file1 is older than file2

For example, if [-x/root] can be used to determine whether the/root directory can be accessed by the current user.

The above are the if keywords for comparison. Yes, the bash process control statements similar to the C language mainly include: if, for, while, until, case and other statements. The following is a detailed introduction.
The IF statement is used to determine and branch. Its syntax rules are very similar to the IF statement in C language. The basic structure is as follows:

If [expression]
Then
# Code block
Fi

Or

If [expression]
Then
# Code block
Else
# Code block
Fi

Or

If [expression]
Then
# Code block
Else if [expression]
Then
# Code block
Else
# Code block
Fi

Or

If [expression]
Then
# Code block
Elif [expression]
Then
# Code block
Else
# Code block
Fi

If you want to put then and if in a row for simplicity, you need to write: If [expression]; then. That is to say, add a ";" sign before then (there is no semicolon at the end of each line in Bash. Do you want to write the content of the two lines to one line? Do you want to use the ";" sign to separate them? Haha, right! In this case, "If [expression]; then" only writes the content of the two rows to one row, and there is nothing new .).

The for loop structure is different from the C language. In bash, the basic structure of the For Loop is:

For $ VaR in [LIST]
Do
# Code block
Done

Where $ VaR is a loop control variable, and [LIST] is a set that VaR needs to traverse. The do/done pair contains the loop body, which is equivalent to a pair of braces in C. In addition, if do and for are written in the same line, you must add ";" before do ";". For example, for $ VaR in [LIST]; do. The following is an example of loop using:

#! /Bin/bash

For day in Sun mon Tue wed Thu Fri Sat
Do
Echo $ day
Done

# If the list is contained in a pair of double quotation marks, it is considered an element.
For day in "Sun mon Tue wed Thu Fri Sat"
Do
Echo $ day
Done

Exit 0

Note that in the preceding example, the variable day in the row where the for is located does not contain the "$" symbol, but is in the loop body, the line variable $ day in which ECHO is located must contain the "$" symbol. In addition, if it is written as for day without the subsequent in [LIST], day will retrieve all the parameters of the command line. Such as this program:

#! /Bin/bash

For Param
Do
Echo $ Param
Done

Exit 0

The above program will list all command line parameters. The loop body of the for loop structure is contained in the do/done pair, which is also characteristic of the while and until loops.

The basic structure of the while loop is:

While [condition]
Do
# Code block
Done

Compile an example to verify this structure.

The basic structure of the until loop is:

Until [condition is true]
Do
# Code block
Done

You can write an example to verify this structure.

Case
The case structure in Bash is similar to the switch statement in C, and can be used for multiple branch control. Its basic structure is:

Case "$ Var" in
Condition1)
;;
Condition2)
;;
*)
Default statments ;;
Esac

The following example uses the case structure for Branch execution:

#! /Bin/bash

Echo "hit a key, then hit return ."
Read keypress

Case "$ keypress" in
[A-Z]) echo "lowercase letter ";;
[A-Z]) echo "uppercase letter ";;
[0-9]) echo "digit ";;
*) Echo "punctuation, whitespace, or other ";;
Esac

Exit 0

The read Statement in the fourth row of "read keypress" in the preceding example indicates that the input is read from the keyboard. This command will be explained in other advanced issues of bash in this handout.

Break/continue
Anyone familiar with C programming is familiar with break statements and continue statements. Bash also has these two statements, and their functions and usage are the same as those in C. The break statement can completely jump out of the current loop body, the continue statement can skip the remaining part of the current loop and directly enter the next loop.

About the shortcut keys of bash in the console

CTRL + u Delete All characters before the cursor
CTRL + D delete a character before the cursor
CTRL + k Delete All characters after the cursor
CTRL + H delete a character after the cursor
CTRL + t change the order of the first two characters of the cursor
CTRL + a move the cursor to the front
CTRL + e move the cursor to the end
CTRL + p command
CTRL + N next command
CTRL + S lock Input
CTRL + q unlock
CTRL + F move the cursor to the next character
CTRL + B move the cursor to the previous character
CTRL + X mark a location
CTRL + C clear the current input

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.