Linux basics-shell script (variables, operators, process control, functions), linux-shell

Source: Internet
Author: User
Tags case statement

Linux basics-shell script (variables, operators, process control, functions), linux-shell

I. shell script

Shell script is a script program written for shell. The shell mentioned in the industry usually refers to shell scripts, but readers should know that shell and shell script are two different concepts.

 

1. Create a shell script hw. sh.

The extension does not affect script execution, but is convenient to indicate the file type.

"#! "Is an agreed tag, which tells the system what interpreter is required to execute this script, that is, which Shell is used.

2. execute shell scripts

A: As an executable program./hw. sh

Note that you must write it. /hw. sh, not hw. sh to run other binary programs. Write hw directly. sh, the linux system will go to the PATH to find if it is hw. sh, and only/bin,/sbin,/usr/bin,/usr/sbin and so on in the PATH. Your current directory is usually not in the PATH, so it is written as hw. sh cannot find the command. /hw. sh tells the system to find it in the current directory.

B: As the interpreter ParameterIn this way, you do not need to specify the interpreter information in the first line, and it is useless to write the script.

Run the interpreter directly. The parameter is the name of the shell script file, for example:

/bin/sh hw.sh/bin/php hw.php

3 .#

The line starting with "#" is a comment and will be ignored by the interpreter.

Sh does not contain comments from multiple lines. Only one # sign can be added to each line.

What should I do if a large code segment needs to be commented out temporarily and the comment is canceled later?

Adding a # symbol to each line is too laborious. You can enclose the code to be annotated with a pair of curly brackets and define it as a function. This function is called everywhere, this code won't be executed, achieving the same effect as the annotation.

2. shell Variables

1. variable naming rules

There is no space between the variable name and equal sign, which may be different from all programming languages you are familiar. Variable names must follow the following rules:

  • Must start with a letter (a-z, A-Z) or underscore (_).
  • There cannot be spaces in the middle, and you can use underscores (_).
  • Punctuation cannot be used.
  • You cannot use keywords in bash (you can use the help command to view reserved keywords ).
  • It is best to add an extension to a file.

2. Variable assignment

A. variable name = value, for example, x = 3, name = "jack"

B. in addition to explicitly assigning values directly, you can also use statements to assign values to variables, for example, for file in 'ls/etc 'to loop the file names in the/etc directory.

3. Use Variables

A. To use a defined variable, you only need to add a dollar sign before the variable name, for example, echo $ x; echo $ name; echo $ {name };

B. The curly braces outside the variable name are optional and can be added without adding them. The curly braces are used to help the interpreter identify the boundary of the variable, for example, the following situation:

For skill in Ada Coffe Action Java do
Echo "I am good at $ {skill} Script"
Done

If you do not add curly brackets to the skill variable and write it as echo "I am good at $ skillScript", the interpreter regards $ skillScript as a variable (its value is null ), the code execution result is not what we expect.

C. Defined variables can be redefined

Iii. shell string

Strings are the most commonly used and useful data types in shell programming (except for numbers and strings, there are no other types of useful data). Strings can be enclosed in single quotation marks, double quotation marks, or no quotation marks. The difference between Single and Double quotation marks is similar to that in PHP.

1. Single quotes

str='this is a string'

Restrictions on single quotes:

  • Any character in single quotes is output as is, and the variable in single quotes is invalid;
  • Single quotes are not allowed in single quotes ).
2. Double quotation marks
your_name='qinjx'str="Hello, I know your are \"$your_name\"! \n"

Advantages of double quotation marks:

  • Variables can exist in double quotation marks.
  • Escape characters can appear in double quotation marks
3. concatenate strings
your_name="qinjx"greeting="hello, "$your_name" !"greeting_1="hello, ${your_name} !"echo $greeting $greeting_1
4. Get the string length
String = "abcd" echo $ {# string} # output 4
5. Extract the substring
String = "alibaba is a great company" echo $ {string: 1: 4} # output liba
6. Search for substrings
string="alibaba is a great company"echo `expr index "$string" is`

Note:In the above script, "'" is a reverse quotation mark, rather than a single quotation mark "'". Do not read the error.

4. Pass parameters through shell

When executing a Shell script, we can pass parameters to the script. The parameters obtained in the script are in the following format:$ N.NRepresents a number, 1 is the first parameter for executing the script, 2 is the second parameter for executing the script, and so on ......

In the following example, we pass three parameters to the script and output them separately.$0Is the execution File Name:

#! /Bin/bash # author: W3Cschool tutorial # url: www. w3cschool. nncho "Shell: Passing parameter instances! "; Echo" executed file name: $0 "; echo" first parameter: $1 "; echo" second parameter: $2 "; echo "third parameter: $3 ";

Set the executable permission for the script and execute the script. The output result is as follows:

$ Chmod + x test. sh $./test. sh 1 2 3 Shell passing parameter instances! Name of the file to be executed: test. sh the first parameter is: 1 The second parameter is: 2 The third parameter is: 3
In addition, there are several special characters used to process parameters:

 

Parameter Processing Description
$ # Number of parameters passed to the script
$ * Display All parameters passed to the script with a single string.
For example, when "$ *" is included in... $ N "to output all parameters.
$ ID of the current process that the script runs
$! ID of the last process running in the background
$ @ It is the same as $ *, but it is enclosed in quotation marks and each parameter is returned in quotation marks.
For example, when "$ @" is included in "... All parameters are output in the form of "$ n.
$- Displays the current options used by Shell, which have the same function as the set command.
$? Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error.

 

 

 

 

 

 

 

 

 

 

V. shell Operators

Like other programming languages, Shell supports multiple operators, including:

  • Arithmetic Operators
  • Relational operators
  • Boolean operator
  • String Operators
  • File test operator

1. Arithmetic Operators

The following table lists common arithmetic operators. Assume that variable a is 10 and variable B is 20:

Operator Description Example
+ Addition 'Expr $ a + $ B 'returns 30.
- Subtraction 'Expr $ a-$ B 'returns 10.
* Multiplication 'Expr $ a \ * $ B 'returns 200.
/ Division 'Expr $ B/$ a' returns 2.
% Remainder The 'expr $ B % $ a' result is 0.
= Assignment A = $ B assigns the value of variable B to.
= Equal. Used to compare two numbers. If the two numbers are the same, true is returned. [$ A = $ B] returns false.
! = Not equal. Used to compare two numbers. If they are different, true is returned. [$! = $ B] returns true.

 

 

 

 

 

 

 

 

 

Note:Conditional expressions must be placed between square brackets with spaces. For example:[$ A = $ B]It is incorrect and must be written[$ A = $ B].

2. Relational operators

Relational operators only support numbers, not strings, unless the value of a string is a number.

The following table lists commonly used Relational operators. Assume that variable a is 10 and variable B is 20:

Operator Description Example
-Eq Returns true if the two numbers are equal. [$ A-eq $ B] returns false.
-Ne Checks whether two numbers are equal. If they are not equal, true is returned. [$ A-ne $ B] returns true.
-Gt Checks whether the number on the left is greater than the number on the right. If yes, returns true. [$ A-gt $ B] returns false.
-Lt Checks whether the number on the left is smaller than the number on the right. If yes, returns true. [$ A-lt $ B] returns true.
-Ge Check whether the number on the left is equal to the value on the right. If yes, true is returned. [$ A-ge $ B] returns false.
-Le

Checks whether the number on the left is less than or equal to the number on the right. If yes, returns true.

[$ A-le $ B] returns true.

 

 

 

 

 

 

 

 

3. boolean operators

The following table lists common boolean operators. Assume that variable a is 10 and variable B is 20:

Operator Description Example
! Non-operation. If the expression is true, false is returned. Otherwise, true is returned. [! False] returns true.
-O Or operation. If one expression is true, true is returned. [$ A-lt 20-o $ B-gt 100] returns true.
- Returns true only when both expressions are true. [$ A-lt 20-a $ B-gt 100] false is returned.

 

 

 

 

4. logical operators

The following describes the Shell logical operators. Assume that variable a is 10 and variable B is 20:

Operator Description Example
&& Logical AND [[$ A-lt 100 & $ B-gt 100] Return false
| Logical OR [[$ A-lt 100 | $ B-gt 100] returns true.

 

 

 

5. String Operators

The following table lists common string operators. Assume that variable a is "abc" and variable B is "efg ":

Operator Description Example
= Returns true if two strings are equal. [$ A = $ B] returns false.
! = Returns true if the two strings are equal or not. [$! = $ B] returns true.
-Z Checks whether the string length is 0. If it is 0, true is returned. [-Z $ a] returns false.
-N Checks whether the string length is 0. If it is not 0, true is returned. [-N $ a] returns true.
Str Checks whether the string is null. If it is not null, true is returned. [$ A] returns true.

 

 

 

 

 

 

6. File test operators

The file test operator is used to detect various properties of Unix files.

Attribute detection is described as follows:

Operator Description Example
-B file Checks whether the file is a block device file. If yes, returns true. [-B $ file] returns false.
-C file Checks whether the file is a character device file. If yes, returns true. [-C $ file] returns false.
-D file Checks whether the file is a directory. If yes, returns true. [-D $ file] returns false.
-F file Checks whether a file is a common file (neither a directory nor a device file). If yes, returns true. [-F $ file] returns true.
-G file Checks whether the SGID bit is set for the file. If yes, true is returned. [-G $ file] returns false.
-K file Check whether Sticky Bit is set in the file. If yes, true is returned. [-K $ file] returns false.
-P file Checks whether the file is a named pipe. If yes, returns true. [-P $ file] returns false.
-U file Check whether the SUID bit is set for the file. If yes, true is returned. [-U $ file] returns false.
-R file Checks whether the file is readable. If yes, true is returned. [-R $ file] returns true.
-W file Checks whether the file is writable. If yes, true is returned. [-W $ file] returns true.
-X file Checks whether the file is executable. If yes, true is returned. [-X $ file] returns true.
-S file Check whether the file is empty (whether the file size is greater than 0). If it is not empty, true is returned. [-S $ file] returns true.
-E file Checks whether a file (including directories) exists. If yes, returns true. [-E $ file] returns true.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Vi. Process Control

1. if else

A. if statement syntax format:

if conditionthen    command1     command2    ...    commandN fi

Write a line (applicable to terminal command prompt ):

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi

The fi at the end is the spelling of if, which will be similar later.

B. if else

If else syntax format:

if conditionthen    command1     command2    ...    commandNelse    commandfi

C. if else-if else

If else-if else syntax format:

if condition1then    command1elif condition2    command2else    commandNfi

If else statements are often used in combination with the test Command, as shown below:

Num1 = $ [2*3] num2 = $[1 + 5] if test $ [num1]-eq $ [num2] then echo 'two numbers are equal! 'Else' two numbers are not equal! 'Fi

2. for Loop

The general format of the for Loop is:

for var in item1 item2 ... itemNdo    command1    command2    ...    commandNdone

Write a line:

for var in item1 item2 ... itemN; do command1; command2… done;

When the variable value is in the list, the for loop executes all the commands once and obtains the current value in the list using the variable name. Command can be any valid shell command and statement. The in list can contain replacement, string, and file name.

The in list is optional. If you do not need it, the for loop uses the location parameter of the command line.

For example, output the numbers in the current list sequentially:

for loop in 1 2 3 4 5do    echo "The value is: $loop"done

Output result:

The value is: 1The value is: 2The value is: 3The value is: 4The value is: 5

Characters in the output string in sequence:

for str in 'This is a string'do    echo $strdone

Output result:

This is a string

3. while statement

The while loop is used to continuously execute a series of commands and read data from the input file. commands are usually used as test conditions. The format is:

while conditiondo    commanddone

The following is a basic while loop. the test condition is: if the int value is less than or equal to 5, the condition returns true. Int starts from 0, and 1 is added to int for each loop processing. Run the preceding script, return numbers 1 to 5, and then terminate.

#!/bin/shint=1while(( $int<=5 )) do         echo $int         let "int++" done 

4. Infinite Loop

Infinite Loop syntax format:

while :do    commanddone

Or

while truedo    commanddone

Or

for (( ; ; ))

5. until Loop

Until executes a series of commands cyclically until the condition is true.

The Processing Method of the until loop is the opposite to that of the while loop.

The while loop is generally better than the until loop, but in some cases-in rare cases, the until loop is more useful.

Until syntax format:

until conditiondo    commanddone

The condition can be any test condition, and the test occurs at the end of the loop, so the loop is executed at least once-please note this.

6. case

Shell case statements are multiple selection statements. You can use the case statement to match a value with a pattern. If the match succeeds, execute the matched command. The case statement format is as follows:

Case value in Mode 1) command1 command2... commandN; Mode 2) command1 command2... commandN; esac

The case method is shown in the preceding figure. The value must be followed by the word in, and each pattern must end with parentheses. The value can be a variable or constant. After matching finds that the value matches a certain mode, all commands are executed ;;.

The value will detect each matching mode. Once the mode matches, the matching mode command is executed and the other modes are not continued. If no matching mode exists, use asterisk * to capture the value and then execute the following command.

The following script prompts you to enter 1 to 4 to match each mode:

Echo: numbers between 1 and 4: 'echo 'the number you entered is: 'read aNumcase $ aNum in 1) echo' you selected 1'; 2) echo 'you selected 2'; 3) echo' you selected 3'; 4) echo 'you selected 4 ';;*) echo 'you have not entered a number between 1 and 4 '; esac

Input different content has different results, such:

Enter a number between 1 and 4: The number you entered is: 3. You selected 3.

Esac

The syntax of case is very different from that of C family. It requires an esac (that is, the case in turn) as the end mark. Each case Branch uses the right parentheses and two semicolons to represent the break.

 

7. Skip Loop

In the loop process, sometimes the loop needs to be forcibly jumped out when the loop end condition is not reached. Shell uses two commands to implement this function: break and continue.

1. break command

The break command can jump out of all loops (all loops following the termination of execution ).

In the following example, the script enters an endless loop until the number entered by the user is greater than 5. To jump out of this loop and return to the shell prompt, use the break command.

#! /Bin/bashwhile: do echo-n "enter a number from 1 to 5:" read aNum case $ aNum in 1 | 2 | 3 | 4 | 5) echo "the number you entered is $ aNum! "; *) Echo" the number you entered is not between 1 and 5! Game ended "break; esacdone

Run the above Code and the output result is:

Enter a number between 1 and 5: 3. The number you entered is 3! Enter a number between 1 and 5: 7 The number you entered is not between 1 and 5! Game ended
2. continue

The continue command is similar to the break command. There is only one difference. It does not jump out of all loops and only jumps out of the current loop.

Modify the preceding example:

#! /Bin/bashwhile: do echo-n "enter a number from 1 to 5:" read aNum case $ aNum in 1 | 2 | 3 | 4 | 5) echo "the number you entered is $ aNum! "; *) Echo" the number you entered is not between 1 and 5! "Continue echo" game ends "; esacdone

When you enter a number greater than 5, the loop in this example does not end.Echo "Game is over! "It will never be executed.

 

VII. Functions

In linux shell, you can define functions and call them in shell scripts.

The Function Definition Format in shell is as follows:

[ function ] funname [()]{    action;    [return int;]}

Note:

  • 1. It can be defined with function fun () or fun () without any parameters.
  • 2. If the parameter is returned, the value "+: return" is displayed. If no value is added, the result of the last command is run as the return value. Return followed by the value n (0-255)

 

1. The following example defines a function and calls it:

#! /Bin/bashdemoFun () {echo "this is my first shell function! "} Echo" ----- function execution started ----- "demoFunecho" ----- function execution completed -----"

Output result:

----- Start to execute the function ----- This is my first shell function! ----- Function execution completed -----

 

2. The following defines a function with a return statement:

#! /Bin/bashfunWithReturn () {echo "This function adds two numbers to the input... "echo" Enter the first number: "read aNum echo" enter the second number: "read anotherNum echo" two numbers: $ aNum and $ anotherNum! "Return $ ($ aNum + $ anotherNum)} funWithReturnecho" returns the sum of the two numbers $? ! "

The output is similar to the following:

This function adds two numbers to the input... enter the first number: 1 enter the second number: 2 the two numbers are 1 and 2! The sum of the two numbers entered is 3!

The Return Value of the function is $? .

Note: All functions must be defined before use. This means that the function must be placed at the beginning of the script until the shell interpreter discovers it for the first time. Only the function name can be used to call a function.

 

 

 

 

References

1. http://www.w3cschool.cn/linux/linux-shell.html

2. http://www.cnblogs.com/linhaifeng/p/6602149.html#_label4

 

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.