Basic shell knowledge

Source: Internet
Author: User

Shell scripts contain several Unix commands or executeProgram.

 

1. Run the shell script

There are two ways to run shell scripts. The first method is to use the sh command to take the shell script file name as a parameter. This method requires that the shell script file has the "readable" access permission.

 

The second method is to use the CHMOD command to set the shell script file so that the shell script has the "executable" access permission. Then, enter the shell script file name at the command prompt.

 

2 exit or exit status

When a Unix process or command stops running, an exit status is automatically returned to the parent process. If the process is successfully executed, an exit status with a value of 0 is returned. If the process encounters an exception during execution but does not end properly, a non-zero error is returned.Code.

 

In a shell script, you can use the "exit [N]" command to return a shell script exit status n to the parent process that calls the script while terminating the execution of the shell script. N must be an integer between 0 and. If the shell script ends with an exit statement without parameters, the exit status of the shell script is the exit status of the Last Command executed in the script.

 

In Unix systems, to test the execution result of a command or shell script, $? The internal variable returns the exit status of the last command previously executed.

 

3. Call the appropriate shell interpreter

The first line of the shell script contains #! It is the text line of the Start flag. This special start flag indicates that the current file contains a group of commands and must be submitted to the specified shell for interpretation and execution. Followed #! It indicates a path name pointing to the command interpreter that executes the current shell script file. For example:

#! /Usr/bin/KSh

If the shell script contains multiple special flag lines, only one flag line works.

 

4 variables

Shell variable names can contain any letter, number, or underline, but the first character must be a letter or underline.

 

All variables in shell are string type, and shell does not distinguish the type of variables.

 

In terms of usage, variables can be divided into internal variables, local variables, environment variables, parameter variables, and User-Defined variables.

Internal variables are variables set by Shell for ease of shell programming. For example, the error type errno variable.

A local variable is a variable defined in a code block or function and is valid only within the defined range.

Parameter variables are the variables passed when a shell script or function is called.

Environment variables are set to provide the runtime environment for the system kernel, system commands, and user commands.

User-Defined variables are common variables or temporary variables set to run a user program or complete a specific task.

 

5 variable assignment

You can use the = Operator to assign values to variables. The syntax format is variable = value. There cannot be spaces before and after the value assignment operator. The value of uninitialized variables is null. You can declare an uninitialized variable using the following Variable assignment form: Variable =

 

6. Internal Variables

Shell provides a wide range of internal variables to support your shell programming.

PWD indicates the current working directory, and its variable value is equivalent to the output of the PWD internal command.

Random, each time this variable is referenced, a random integer in the range of 0-32767 is generated evenly.

Sconds: the time (in seconds) when the script has been run ).

Ppid, the ID of the parent process of the current process.

?, $? Variable indicates the exit status of the last command or shell script executed.

 

7. Environment Variables

Editor, used to determine the editing program used for command line editing, usually vi

Home, home directory

Path: Specifies the retrieval path of the command.

 

8. variable reference and replacement

Assuming that variable is a variable, you can add the "$" prefix before the variable name to reference the variable value, that is, replace the variable name with the value stored in the variable.

 

Several variables can be referenced: $ variable and $ {Variable}

 

Note: variables in double quotation marks can be replaced, but those in single quotation marks cannot be replaced.

 

9 indirect reference of Variables

Assuming that the value of a variable is the name of another variable, you can obtain the value of the third variable based on the first variable. For example, message = Hello

Hello = "good morning" Using echo "Now message =/$ message" will return now message = Good morning.

 

$ {Var: = value}. If the variable VAR is not set or its value is null, the value is used to assign a value to the variable VAR and replace the variable.

$ {Var = value}, regardless of whether VaR has a value, will be replaced with value.

 

10-position Parameter

The parameters uploaded from the command line to the shell script are also called location parameters. The order in which location parameters appear references $0, $1, and $2.

 

$0 is the name of the shell script file. The shell process is responsible for setting the $0 parameter.

$1 is the first parameter, $2 is the second parameter, and so on. However, starting from the tenth position parameter, curly brackets must be used. For example: ${10 }.

Special variables $ * and $ @ indicate all location parameters, and $ # indicate the total number of location parameters.

 

Use the SET command to set the value of the location parameter. For example, set a B c sets $1, $2, and $3 to A, B, and C respectively. The command echo $ * is used to output the values of all configured command parameters.

 

11 variable declaration and Type Definition

Although shell does not strictly distinguish the types of variables, in Korn shell and Bash, you can use the typeset or declare command to define the types of variables and initialize them at definition.

 

The Korn shell uses typeset to set the attributes of the variable. Using the-I Type Selection of the typeset command, you can declare the variable as an integer variable. For example:

Typeset-I number

Number = 3

Echo "number = $ number"

 

12 commands

: The True statement does not perform any actual processing actions, but can be used to return a test condition with an exit status of 0. These two statements are often used in the while loop structure's infinite loop test condition.

 

Echo and print commands. Print functions are exactly the same as Echo functions. It is mainly used to display various information.

 

READ command. The main function of a read statement is to read standard input data and store it in variable parameters. If the READ command is followed by multiple variable parameters, the input data is assigned values for each variable in the order of separated words by spaces. The variable parameter of the read statement can be followed by a prompt string. For example, read data? "Please enter data"

 

Set and unset commands. The set command is to modify or reset the value of the location parameter. Shell requires that you cannot directly assign values to location parameters. Using a set without parameters will output all internal variables.

Set -- to clear all location parameters.

The unset command is used to clear shell variables and set the variable value to null. This command does not affect the location parameter.

 

The expr command is used to calculate the value of an expression, and then sends the calculation result to the annotation output. The expression can be a string comparison expression, an integer arithmetic expression, or a pattern matching expression. Syntax format: expr expression

Integer arithmetic expressions supported by the expr command:

Exp1 + exp2: calculates the sum of the expressions exp1 and exp2

Exp1-exp2, calculating the difference between expressions exp1 and exp2

Exp1/* exp2: calculates the product of the expressions exp1 and exp2.

Exp1/exp2, the operator that calculates the expressions exp1 and exp2

Exp1 % exp2, returns the remainder of the expressions exp1 and exp2.

 

The expr command supports the following string comparison expressions:

Str1 = str2, the comparison string str1 is equal to str2. If the calculation result is true and 1 is output at the same time, the return value is 0. Otherwise, if the calculation result is false, 0 is output, but 1 is returned.

Other comparison operators:/>,/<,/> =,/<= ,! =

 

The let Command replaces and extends the integer arithmetic operation of the expr command. In addition to the five arithmetic operations supported by Expr, The let command also supports + =,-=, * =,/=, and % =

 

13 numerical Constants

The shell script interprets numeric characters in a string in decimal format, unless there is a special prefix or mark before the number. If there is a 0 before the number, it indicates the number of an octal, and 0x or 0x indicates the number of a hexadecimal number. Base # number indicates the base number (2-64) and number. For example:

Let "Oct = 032"

Echo "Oct number = $ Oct"

 

Let "bin = 2 #1010"

Echo "binary number = $ bin"

 

14. Command replacement

The purpose of command replacement is to obtain the command output and assign values to the variable or perform further processing on the command output. Command replacement implementation method: use the $ (...) form to reference the command or use reverse quotation marks to reference the command, 'command'

For example:

Today = $ (date)

Echo $ today

The delete file filename contains the list of objects to be deleted. Rm $ (cat filename)

 

15 test statement

The test statement and the IF/then and case structure statements constitute the Control Transfer Structure of shell programming.

 

The main function of the test command is to calculate the following expression, check the attributes of the file, compare the string or compare the integer of the string connotation, the result of the expression is used as the exit state of the test command. If the exit status of the test command is true, 0 is returned. If it is false, a non-0 value is returned.

 

The syntax format of the test command is test expression or [expression]. Note that there must be a space on both sides of the square brackets.

 

[[Expression] is a more common test structure than [expression], and also extends the test command.

 

16 file test operators

File testing mainly refers to testing the File status and attributes, including whether the file exists, the file type, the file access permission, and other attributes.

 

File property test expression

-A file. If the specified file exists, the test result is true.

-R file: If the given file exists and its access permission is readable by the current user, the result of the condition test is true.

-W file: if the specified file exists and its access permission is writable by the current user, the test result is true.

-X file: if the specified file exists and its access permission is executable by the current user, the result of the condition test is true.

-S file. If the specified file exists and its size is greater than 0, the test result is true.

-F file: if the specified file exists and is a common file, the result of the conditional test is true.

-D file: if the specified file exists and is a directory, the result of the conditional test is true.

-L file: if the specified file exists and is a symbolic link file, the test result is true.

-C file: if the specified file exists and is a special character file, the result of the conditional test is true.

-B file: if the specified file exists and is a special block file, the test result is true.

-P file: if the specified file exists and is named as a pipe file, the result of the condition test is true.

F1-ed F2: If the given files F1 and F2 exist and point to the same physical file, the test result is true.

 

String test operator

-Z str: if the length of the given string is 0, the result of the condition is true.

-N str: if the length of the given string is greater than 0, the test result is true. The string must be enclosed in quotation marks.

S1 = S2. If the given string S1 is equivalent to the string S2, the test result is true.

S1! = S2. If the given string S1 is not the same as the string S2, the test result is true.

S1 <S2. If the given string S1 is smaller than the string S2, the test result is true. Example:

If [["$ A" <"SB"]

If [["$ A"/<"$ B"], escape characters must be added before the characters <and> In the case of square brackets.

S1> S2. If the given string S1 is greater than the string S2, the test result is true.

 

In the test statement that compares strings, double quotation marks must be added before and after variables or string expressions.

 

Integer test operator

The comparison of integer values in the test statement automatically usesC LanguageThe atoi () function in converts a character to an equivalent ASC integer. Therefore, you can use numeric strings and integer values for comparison.

 

Integer test expression:-eq (equal to),-NE (not equal to),-GT (greater than),-lt (less than),-Ge (greater than or equal ), -Le (less than or equal)

 

17 logical operators

(Expression) is used to calculate the combination expression in parentheses. If the calculation result of the entire expression is true, the test result is also true.

! Exp: performs a non-logical operation on the expression, that is, inverse of the test result. Example: test! -F file1

Symbol-A or & indicates logic and operation, and symbol-O or | indicates logic or operation.

 

========================================================== ==============================================

 

Reference extension:

 

Basic Linux-shell knowledge

 

Linux Shell learning Summary (updating ......)

 

 

Linux make (makefile) from simple to deep learning and Example Analysis

 

 

Shell if statement example: whether the file or directory exists or has the execution permission

 

Add two files in Linux

 

 

 

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.