Operation of shell scripts, etc.

Source: Internet
Author: User
Tags arithmetic arithmetic operators define function echo command

1 , command substitution: '

Inverted single quotes, also called heavy notes. On the keyboard and the ~ key together of the key yo, do not knock into single quotation marks.

A

After using ", the shell first replaces the date command enclosed in the output, and then executes the entire output command."

B, command substitution can also be used to store command output in variables, as follows:

The variable Ctr will contain a count of the files in the current directory whose names end in. txt.

2. Expr

Most shells do not support numeric variables, and all variables are used as strings. In the case of var=25, variable var contains a string consisting of character 2 and character 5, not the number 25.

The expr command evaluates an arithmetic expression, and the output of the command is sent to the standard output.

As shown, expr 4 + 5 does an integer addition operation, which outputs 9.

The arithmetic operators supported by the expr command are: + 、-、 *,/,%. However, the * needs to be escaped with \, otherwise the shell will treat * as a wildcard character as shown in:

Note: With the expr command, you must add a space between the left and right sides of the arithmetic operator. As shown, arithmetic operations are not performed when spaces are not added:

In addition, the expr command supports only integer operations and does not support decimals, as shown below, using decimals to obtain the correct arithmetic results:

The output of the expr command is sent to the standard output, and if you want the output to be stored in a variable, you can replace it with the command:

3 , typeset - I.

Bash and ksh shells provide limited support for integer variables. We can use the Typeset–i variable name to define an integer variable that can be used to perform arithmetic operations directly with the integer variable.

4 , evaluates an expression, returns " really " or " Fake " test/[] ( square brackets )

Typically, test or [] is used to evaluate whether the condition is true or not. The syntax is as follows:

Test expression

[Expression]

Note that after the test, add a space before writing the expression. When using [], the left and right sides of an expression need to add spaces. The comparison operator for an expression needs to add a space on both sides.

When the expression contains multiple conditions, you can use the option-A and-O:

-A: The condition is set at the same time, with, and means,

-O: A condition can be established, or, the meaning of OR

Test/[] is mainly used in programming constructs, so we are in the following programming constructs section, concretely demonstrates its usage.

5. If construction

If the constructor is the same as the IF statement in Java, the syntax differs

If construction syntax:

If condition (s)

Then command (s)

[Else command (s)]

Fi

The IF construct must end with FI, and the else part is not required, depending on the usage scenario.

If...elif Construction

If condition (s)

Then command (s)

elif Command (s)

else command (s)

Fi

An if construct can have multiple elif statements, but only one fi to end the construct, and else can have at most one.

Classroom Exercises:

In the shell script, the script file is named Testif.sh, which implements the following functions:

1. Prompt the user to enter the score

2, read the user input scores put in the variable mark

3, if mark>= 80, prompting the user "you is excellent!"

mark>= && Mark <80, prompting "hei,guy,you is good."

Mark >= && Mark < 70, prompting "it is OK."

Mark <60, prompting "Oh, guy, it's so bad,you should."

Comparison operators in arithmetic tests use the following options to represent

equals-eq

Not equal to-ne

Greater than or equal to-ge

Greater than-GT

Less than or equal to-le

Less than-LT

The following are the statements in the shell script file:

Code Execution Effect:

Where the judgment condition is written, it can be used in addition to test, such as:

6 , Case Construction

Case ... Esac construction syntax is:

Case $variable-name in

value1) command (s);

value2) command (s);

.

.

.

*) command (s);;

Esac

The construct is used to execute a specific set of instructions in a shell script based on the value of the variable, evaluate the value of the variable, and compare it to each value specified. When a variable value matches one of the specified values, the set of commands specified under that value is executed.

Classroom Exercises:

1, write a shell script, the file name is testcase.sh

2, the first line prompts the user to enter the digital grade:

Read the user-entered grade in the same line of the cue message, and put it in the variable grade

3, if the user input is 1, it shows freshman

If the user enters 2, the sophomore is displayed.

If the user enters 3, the junior is displayed.

If the user enters 4, the senior is displayed.

If the user enters a different content, the NI cai is displayed

This feature is required to be implemented using case.

The following are the statements in the shell script file:

When using case construction, the last command executed for any variable value must be followed by a pair of semicolons that separates the commands in the set of commands executed for the next value.

7 , while construction

Syntax for While loop:

While condition (s)

Do

Command (s)

Done

Here, as long as the condition is true, execute the middle command of do and done.

b Reak and Continue statements

The break and continue commands can be used with a while loop. Break exits the entire loop, continue means exiting the current loop and starting the next loop.

The execution effect is as follows:

Classroom Exercises:

1, write a shell script, the file name is testwhile.sh

2. Use the while loop to print out the numbers between the 1--10

The following are the statements in the shell script file:

Or:

Execution effect:

8 , until structure

Until usage is the same as while, but when the condition is not true, that is, when the condition is false, the loop is entered, and the condition is real, ending the loop.

9. For construction

For loop syntax:

For variable_name in <list_of_values>

Do

...

...

Done

The For loop takes a column of values as input and executes the loop for each value in the loop, that is, the command between do ... done.

A column value in a For loop is delimited by one or more spaces. 1--9 can be represented with {1..9}

Classroom Exercises:

Write the shell script file and output the 99 multiplication table:

The function of the echo command after option E is to have the following character ' \ t ' displayed as a special character, the TAB key, rather than as plain text output.

Execution effect:

add: Seq

The SEQ statement is used to generate all integers from one data to another, that is, a sequence, and you can specify the difference between two integers in a sequence, which is the stride that the sequence grows. When you specify only the starting and ending values of a sequence, the STRIDE is 1, and when you specify only one value, the default value is the end, the sequence starts from 1, the STRIDE is 1, and when you specify a stride, you need to specify the starting value, specify the stride, and finally specify the end value. As shown in the following:

By changing the inner loop of the above 99 multiplication table into a for loop, you can use the output of the SEQ statement in the inner loop as the column value that the inner loop needs to loop:

Ten , Exit

Exit exit from the shell script based on the results of the test command, that is, stop execution and return the prompt. The exit command can be used in the If or else section of the IF construct.

The results of the above script execution:

When the user enters Y, the exit is not performed in the echo "want to quit." Statement.

In addition, the Exit command can be written as Exit N,n as an arbitrary integer. Where integer 0 indicates success, other non-0 values indicate different reasons for failure. In the 99 multiplication table above, exit 0 is used.

11. Test Command Review

The test command, in conjunction with constructs such as if or while, examines the value of a variable in addition to three other uses:

A , the test command option tests the file status

Test the file status of the various options, not listed here, see the textbook page 6.11.

An example is listed below:

The above script performs the effect:

B , test for arithmetic testing

The test command, combined with if, tests the values of the variables, and the arithmetic test operators and usages represented by each option are shown in the If construction section above.

C , the test command tests the string

The string test operator is shown on page 6.13 of the textbook.

12. Create a function

A function is a statement block that is referenced by the same name and used to perform a specific task. When you need to perform the same task repeatedly, you should create a function for the task that invokes the function by specifying the function name. The function must first be defined and then called.

Define function Syntax:

function <function_name>

{

<commands>

}

(1) Define the function F1 in the shell script file and add the calling function statement. Functions can be called from a function name in a shell script file, after the function is defined:

After executing the above script file:

(2) After the command prompt, define the function F2 and call the function

(3) Pass parameters to the function. Use their location to refer to the arguments passed to the function, that is, the use of positional parameters when defining the function.

Define functions Listdir, Viewfile, cpfile in shell script files

If a function is defined only in a shell script file and no function statement is called, then the shell script file is executed, and the function is created and not called. And after the current shell is the command prompt, these functions cannot be called directly.

After executing the source script file name statement, you can invoke the defined function in the current shell. As shown below:

For positional parameters, the following is shown below.

- , handling parameters in a shell script

Parameters are used to pass arguments from the command line to the shell script. A parameter can be any value, usually a file name or string, which is a command name or file name that is specified after the shell prompt. In the script, the argument is referenced as a self-variable.

After the shell interprets the command as Liunx, enters the command and presses ENTER, the shell places each word in the command line into a special variable in the following way:

The first word in the command line, the command name, is put into a variable called $ A.

The first argument in the command line, the second word in the command line, is placed in the variable $ $.

The second argument in the command line, the third word in the command line, is placed in the variable $.

With the exception of $ A, the shell can create up to 9 variables correctly, and the values stored after 9 will no longer be accurate. $ to $9 is also known as the location parameter of the command line. Depending on the number of parameters specified in the command, the shell assigns values to some or all of these variables.

The shell also assigns values to the following variables:

$*: Contains the entire string of parameters

$#: Contains the number of parameters specified in the command

Here's a quick example of how to set positional parameters:

The following results are performed:

Use positional parameters to implement copying files:

Execution effect:

- , Shift command

The shell creates a maximum of 9 positional parameters, $0--$9. The value stored from the 10th start parameter will no longer be correct.

Test the scenario where the user input parameter exceeds 9, as shown below:

Execute the script file, enter multiple parameters, found that the value of the $ $ parameter stored in the parameter append 0,$11 parameter is stored with the value of the parameter append 1, which does not match the actual input:

In practice, there may be more than 9 user input parameters, and the Shift command allows the user to enter a variable number of parameters, including more than 9 scenes, and shift can be used multiple times.

In this example, the shift command effect explains:

This example is used to help users copy or function files, if the script file name after the input C indicates that the user wants to copy the file, enter d indicates that the user wants to delete the file. When entering other, the user is prompted with the parameter only C or D.

The following results are performed:

the ,. bash_file Files

The. bash_file file is a special file that executes when the user logs on to the system. The file is optional, exists in the user's home directory, is a hidden file, the LS command, the-a option can view hidden files:

- , here documentation

The input to a command or shell script is usually contained in a separate file, which is then supplied as a parameter to the script. You can also include the input data in the shell script itself, and then the data is considered to be in a here document, that is, the input is here, not in a file somewhere else. The << operator implements this type of construct.

<< operator Usage:

Command << pattern

Pattern

The contents of the above two pattern are treated as inputs, so the pattern must appear in pairs, and if the second is missing, it will be assumed that everything from the first pattern to the end of the file is the input and is not considered a special command.

Pattern is just an identifying function that can be represented by any string. The second pattern requires a freeze-up.

One use of the here document is to display the menu, which is an effective way to build a menu screen compared to using multiple echo statements.

We use the here document to rewrite the previous while loop with the selection menu:

Execution effect:

- , debugging shell scripts

Use the SET command to debug the shell script with the-X,-v option.

The following example calls the-X or-v option in the sh <filename> command:

SH - v <filename> :

When you execute a script, you first display each line of statements written in the script, and then display the results after the statement is executed

SH - x <filename> :

Similar to Sh-v <filename>, each line of statements written in the shell file is displayed, but the-x option adds a + in front of each line of statements, and also replaces each statement and expression with the value of the variable, and then displays the result of the statement's execution.

Operation of shell scripts, etc.

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.