Linux script programming (shell) shallow (reprint)

Source: Internet
Author: User
Tags save file uppercase letter vars

Linux script (shell) programming

Ah, yesterday on the Internet to see an article about Linux/unix shell, think of their last write this thing is also a year ago, think about it is almost forgotten.

or tidy up, do a review, it may be used in the future, post out, convenient for the first time to learn this thing fellow.

If you find something wrong, please point it out, and I'll be grateful for a word. Say less nonsense!!!

The most important scripting language under Linux is bash, and I'll just write about it (I'll just do this:)). Compared to other development languages (such as C), Bash is a simpler language, mainly used to write script code, some batch processing or installation programs. You can look at the/etc/init.d/directory where there is a lot of script files to control the various services.

First look at a "Hello world!" Examples of:
Create a new file in a directory called hello.sh, typing the following code:

#!/bin/sh
echo "Hello world!"

All right, that's all. Save, and at the command prompt, go to the directory where "hello.sh" is saved so that it executes:

#sh hello.sh (carriage return)
Did you see that? Haha, but it's not too early for you to be happy, it just doesn't explain what you're doing in other programming environments like "Hello World." , the distance from the master is still far away.

Let's look at the use of variables in the bash script first.
Modify the "Hello world!" above example, change to the following look:

#!/bin/bash
# This was a very simple example
str= "Hello world!"
Echo $str

After saving, follow the above method to execute the script, and you will see the same effect as before. Let's look at the meaning of each sentence:
First line, #! is a description of the type of hello.sh file, which is somewhat similar to the meaning of a file suffix used to represent different file types under Windows systems. The Linux system determines the type of the file based on "#!" and the information that follows the string. The "#!" and the "/bin/bash" in the first line of bash indicate that the file is a bash program that needs to be interpreted by the Bash program in the/bin directory. BASH This program is usually stored in the/bin directory. The wording of this line is fixed.
The second line of "# is a ..." is the Bash program comment, in the bash program from the "#" number (no "!") The beginning to the end of the line is considered a program comment, which is equivalent to the "//" in the C + + language.
The third line assigns a value to a variable called Str.
The function of the Echo statement in line four is to output the contents of the string or variable behind echo to the standard output. Note that there is no semicolon at the end of most statements in BASH.

For the third row, one might ask: what is the type of the variable str in c/s + +? In BASH, variable definitions are not required, and there is no definition process like "int i". If you want to use a variable, as long as he is not defined in front, it can be used directly, of course, you use the variable's first statement should be assigned to him the initial value, if you do not assign the initial value is OK, but the variable is empty (note: Is null, not 0).

For the use of variables, the following points should be noted:
One, when the variable is assigned, "=" cannot have spaces on either side;
Second, the end of the statement in BASH does not require a semicolon (";") );
Third, in addition to the variable assignment and in the For Loop statement header, the variable used in BASH must have a "$" symbol in front of the variable.

In a more detailed bash document, the use of variables is stated in the following form: ${str}, if your script makes a baffling mistake, you might want to see if this is the problem.

Since the variables in BASH do not need to be defined, there is no type to say whether it is a variable that can hold an integer or a string. Right!
A variable can be defined as a string, or it can be redefined as an integer. If an integer operation is performed on the variable, he is interpreted as an integer, and if the string is manipulated, he is treated as a string. Take a look at the following example:

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

Take a look?

There's a new keyword: let. For integer variable calculation, there are several: "+-*/%", they mean the same as the literal meaning, in * and/before must be prefixed with a backslash, has been anti-Shell first explained. Integer operations are generally implemented by the two instructions of let and expr, such as a variable x plus 1 can be written: let "x = $x + 1" or x= ' expr $x + 1 '


With regard to runtime parameters, we sometimes would like to pass a parameter when executing a script, such as: #sh mysh.sh HDZ (carriage return) good, very simple, in bash, use such a variable passed in the front with the "$" symbol.

$# the number of command-line arguments passed into the script;

$* all command-line parameter values, leaving a space between the values of each parameter;

Positional variable

The $ A command itself (shell file name)

The first command-line argument;

$ A second command-line argument;

...

OK, edit the following script:
#!/bin/sh

echo "Number of VARs:" $#

echo "Values of VARs:" $*

echo "Value of VAR1:" $
echo "Value of VAR2:" $
echo "Value of VAR3:" $
echo "Value of VAR4:" $4

Save file name my.sh, pass in Parameters when executing: #sh my.sh a b C d e (carriage return), you will be more aware of the meaning of each variable when you see the result. If the parameter accessed is not passed in at execution time, there is a code like this:
echo "Value of VAR4:" $

Instead of entering 100 parameters at execution time, the obtained value is NULL.

In a BASH program, if a variable is used, the variable is 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 with the local keyword when the variable is first assigned to the initial value, as in the following example:

#!/bin/bash
hello= "Var1"
Echo $HELLO
function Hello {
Local hello= "Var2"
Echo $HELLO
}

Echo $HELLO

The result of the execution of the program is:

Var1
Var2
Var1

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

The difference between a variable in BASH and a variable in the C language
Here we are not familiar with BASH programming, but very familiar with the C language programmer to summarize the use of variables in the bash environment to pay attention to the problem.

Variables in 1,bash need to precede the variable with a "$" symbol (the first assignment and the "$" sign in the head of the For loop);
There are no floating-point operations in the 2,bash, so there are no floating-point variables available;
The comparison symbol of the shaping variables in 3,bash is completely different from the C language, and the arithmetic operations of the shaping variables need to be handled by let or expr statements;

Let's look at the comparison between variables:
In the comparison operation, the integer variable and the string variable are different, as described in the following table:

Corresponding action    Integer action string action
same          -eq          =
Different          -ne        ! =
Greater than          -gt         
Less than          -lt          <
greater than or equal to    -ge
less than or equal to    -le
For empty                       -Z
is not empty                     -N


Like what:
Compare integers A and b for equality write if [$a = $b]
Determine if integer A is greater than integer b to write if [$a-gt $b]
To compare strings A and b for equality write: if [$a = $b]
To determine if string A is empty write: if [-Z $a]
Determine if integer variable A is greater than B to write: If [$a-gt $b]

Note: There are spaces left and right around the "[" and "]" symbols.

Bash is the Shell of the Linux operating system, so the file of the system must be an important object that bash needs to manipulate
operator, let's talk about the operation of the file:

Meaning (returns TRUE if the following requirements are met)

-e file already exists
-F file is a normal file
-S file size is not zero
-d file is a directory
-R file can be read by the current user
-W file can be written to the current user
The-x file can be performed on the current user
-G file GID flag is set
The UID flag of the-u file is set
-O file belongs to the current user
-G file has the same group ID as the current user
file1-nt file2 file file1 than file2 update
File1-ot file2 file file1 older than file2

If [-x/root] can be used to determine whether the/root directory can be entered by the current user.


There is the IF keyword to compare, yes, Bash has a similar process Control statement in C language, mainly: if, for, while, until, case and other statements. Here is a more detailed introduction.
The IF statement is used for judging and branching, and its syntax rules are very similar to the if of the C language. Several of its basic structures are:

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 on one line for brevity, then write this: if [expression]; Then That is, add a ";" before then. Number (there is no semicolon at the end of each line in bash, so write the contents of the two lines to one line, whether you want to use ";" The number is separated? Haha, yes! In this way, "if [expression]; Then "just write two lines of content to a line, nothing new." )。

The For loop structure differs from the C language in that the basic structure of the For loop in BASH is:

For $var in [list]
Do
#code Block
Done

Where $var is the loop control variable, [list] is a collection that Var needs to traverse, Do/done contains the loop body, which is equivalent to a pair of curly braces in the C language. In addition, if do and for are written on the same line, you must precede do with ";". such as: for $var in [list]; Do. Here is an example of using a For loop:

#!/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 quotes, 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 example above, the variable day in the for row is not marked with a "$" symbol, and in the loop body, the Echo row variable $day must be prefixed with "$". In addition, if you write for-day without a subsequent in [list] part, Day will take 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 included in the Do/done pair, which is the feature of the later while and until loops.

The basic structure of the while loop is:

while [condition]
Do
#code Block
Done

This structure invites you to write an example to verify.

The basic structure of the Until loop is:

Until [condition is TRUE]
Do
#code Block
Done

This structure also invites you to write an example to verify.

Case
The case structure in BASH is similar to the function of a 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 procedure is an example of a branch execution using the case structure:

#!/bin/bash

echo "hit a key and 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 line Fourth of "read Keypress" in the above example indicates that input is read from the keyboard. This command will be explained in the other advanced questions of BASH in this handout.

Break/continue
Familiar with C programming is familiar with break statements and continue statements. BASH also has these two statements, and the function and usage are the same as in the C language, the break statement can let the program flow out of the current loop, and the continue statement can skip the remainder of the loop and go directly to the next loop.


About bash shortcut keys in the console

Ctrl+u Delete all previous characters of the cursor
Ctrl+d Delete a previous character of 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 a cursor
CTRL + A moves the cursor to the front
Ctrl+e move cursor to the last face
Ctrl+p Previous Command
CTRL + N Next command
Ctrl+s Lock Input
Ctrl+q unlock
CTRL+F move the cursor to the next character
CTRL+B move cursor to previous character
Ctrl+x Mark a location
CTRL + C clears the current input

Original link

http://blog.csdn.net/compiler_hdz/article/details/575113

Linux script programming (shell) shallow (reprint)

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.