Shell learning Summary

Source: Internet
Author: User

Author: Wang Shanshan,Hua Qing vision embedded college lecturer.

I. Differences and usage between system variables, user variables, and environment variables in shell:

Shell has the following basic types of variables:

1) environment variables defined by Shell

At the beginning of execution, shell has defined some variables related to the system's working environment. You can also redefine these variables. Common shell environment variables include:

Home:The full path name used to save the registration directory.
  Path:Used to save the directory path names separated by colons. Shell searches for these directories in the order given in the PATH variable. The first executable file with the same name as the command will be executed.
  Term:The type of the terminal.
  UID:The identifier of the current user. The value is a string consisting of digits.
  PWD:The absolute path name of the current working directory. The value of this variable varies with the use of the CD command.
  PS1:Primary prompt. for privileged users, the default primary prompt is "#". For common users, the default primary prompt is "$ ".
  PS2:When the shell receives the user's input command, if the user enters "/" at the end of the input line, then press enter, or, when the shell determines that the command entered by the user is not over when the user presses the Enter key, the pop-up prompt is displayed, prompting the user to continue entering the rest of the command. The default pop-up prompt is "> ".

2) User-Defined variables

You can define your own variables according to the following syntax rules:

Variable name = variable value

Note that "$" should not be added before the variable name when defining the variable, and "$" should be added before the variable name When referencing the variable content "; when assigning values to variables, spaces must not be left on both sides of the equal sign. If the variable itself contains spaces, the entire string should be enclosed in double quotation marks.

When writing a shell program, we recommend that you use uppercase letters to indicate all variable names to distinguish them from command names.

Sometimes we want to explain a variable and set it to a specific value without changing its value. This can be ensured by the following command:

Readly variable name

At any time, the created variables are only local variables of the Current Shell, so they cannot be used by other commands or Shell programs run by the shell, the Export command provides a local variable to other commands executed by shell in the format:

Export variable name

You can also use the Export command when assigning values to variables:
Export variable name = variable value

Variables described in export can be accessed in all commands or programs run after shell.

3) location parameters

A location parameter is a variable that is determined by its location in the command line that calls the shell program. It is a parameter entered after the program name. Location parameters are separated by spaces. Shell replaces $1 with the first location parameter in the program file, and the second with $2, and so on. $0 is a special variable whose content is the file name of the current shell program. Therefore, $0 is not a location parameter, $0 is not included when all the current location parameters are displayed.

4) predefined Variables

Predefined variables are similar to environment variables and are also defined at the beginning of shell. The difference is that users can only use these variables according to shell definitions, you cannot redefine it. All predefined variables are composed of the $ operator and another symbol. Common shell predefined variables include:

$ #: Number of location parameters
$ *: Content of parameters at all locations
$? : Status returned after the command is executed
$: Process ID of the current process
$! : The last process number running in the background
$0: name of the currently executed process

Where, "$ ?" This command is used to check whether the execution of the previous command is correct (in Linux, the exit status of the command is 0, indicating that the command is correctly executed, and any non-0 value indicates that the command has an error ).

The most common use of the '$' variable is to use it as the name of a temporary file to ensure that the temporary file will not be repeated.

5) variable of parameter replacement

Shell provides the parameter replacement capability so that you can assign different values to variables based on different conditions. There are four types of parameters for parameter substitution. These variables are usually associated with a location parameter and determine the value of the variable based on whether the specified location parameter has been set to a class, their syntax and functions are as follows.

A. Variable =$ {parameter-word }:If a parameter is set, replace the value of the parameter with the value of the variable. Otherwise, replace the value with word. That is, the value of this variable is equal to the value of a parameter. If this parameter is not set, the variable is equal to the value of word.
B. Variable =$ {parameter = word }:If a parameter is set, the value of the parameter is replaced with the value of the variable. Otherwise, the variable is set to word and then the value of the parameter is replaced with word. Note that location parameters cannot be used in this way, because location parameters cannot be assigned values in Shell programs.
C. Variable =$ {parameter? Word }:If a parameter is set, the value of the parameter is used to replace the value of the variable. Otherwise, word is displayed and exited from shell. If word is omitted, standard information is displayed. This variable must be equal to the value of a parameter. If this parameter is not set, a message is displayed and then exited. Therefore, this method is often used for Error Indication.
D. Variable =$ {parameter + word }:If a parameter is set, replace the variable with the word parameter. Otherwise, replace the variable with the word parameter.

In all these four forms, the "parameter" can be either a location parameter or another variable, but there are many situations where the location parameter is used.

2. Process Control for Shell Program Design

1) test command

The test command is used to check whether a condition is true. It can be used to test values, characters, and files. The test characters and corresponding functions are as follows:

(1) numerical test:

-EQ: true if it is equal
-Ne: true if not equal
-GT: true if the value is greater
-Ge: true if the value is greater than or equal
-Lt: true if the value is smaller
-Le: true if the value is less than or equal

(2) string test:

=: Equal to true
! =: True if not equal
-Z string: the pseudo-String Length is true.
-N string: the string length is true if it is not pseudo.

(3) file test:

-E file name: true if the file exists
-R file name: true if the file exists and is readable
-W file name: true if the file exists and can be written.
-X file name: true if the file exists and can be executed
-S file name: true if the file exists and contains at least one character
-D file name: true if the file exists and is a directory
-F file name: true if the file exists and is a normal file
-C file name: true if the file exists and is a special character file
-B file name: true if the file exists and is a special file.

In addition, Linux also provides , Or ("-O), non ("-a ") three logical operators are used to connect test conditions, the priority is:"!" Highest, followed by "-a", and "-o.

Bash can also perform simple arithmetic operations in the following format:

$ [Expression]
Example: var1 = 2
Var2 = $[var1*10 + 1]
Then, the value of var2 is 21.

2) If Condition Statement

The condition branch in the shell program is implemented through the IF Condition Statement. The general format is:

If condition command string
Then
Command string when the condition is true
Else
Command string when the condition is false
Fi

3) For Loop

The for loop executes a command sequence for all possible values of a variable. The values assigned to the variable can be provided in the form of a numerical list in the program, or in the form of a positional parameter outside the program. The general format of the For Loop is:

For variable name
[In Value List]
Do
Several command lines
Done

The variable name can be any string selected by the user. If the variable name is Var, the value given after in replaces $ VaR in the circular command list in sequence. If in is omitted, the value of VaR is the location parameter. Every possible value assignment to a variable will execute the command list between do and done.

4) while and until Loops

Both the while and until commands use the return status value of the command to control the loop. The general format of the while loop is:

While
Several command lines 1
Do
Several command lines 2
Done

As long as the return status of the last command in "Several command line 1" in while is true, the while loop continues to execute "Several command line 2" between do... done ".

The until command is another loop structure, which is similar to the while command in the following format:

Until
Several command lines 1
Do
Several command lines 2
Done

The difference between an until loop and a while loop is that a while loop continues to run when the condition is true, while an until loop continues to run when the condition is false.

Shell also provides two commands, true and false, to create an infinite loop structure. Their return states are always 0 or not 0.

5) Select case conditions

The IF Condition Statement is used to select one of the two options, and the case condition selection provides you with a method to select one from multiple options based on the string or variable value. The format is as follows:

Case string in
Exp-1)
Several command lines 1
;;
Exp-2)
Several command lines 2
;;
......
*)
Other command lines
Esac

By calculating the string value, shell compares the result to the expression exp-1, exp-2, and so on until a matching expression is found, if a match is found, execute the following command until a semicolon (;) is encountered.

You can also use shell wildcards ("*", "?" , "[]"). Generally, "*" is used as the final expression of the Case command to execute the "other command line" command when no matching item is found.

6) unconditional control statement break and continue

Break is used to terminate the execution of the current loop immediately, while contiune is used to start the execution of the next loop immediately without executing the statements following the loop. These two statements are valid only when they are placed between do and done.

7) Function Definition

You can also define functions in shell. A function is actually composed of several shell commands, so it is similar to a shell program in form. The difference is that it is not a separate process, but a part of the shell program. The basic format of the function definition is:

Functionname
{
Several command lines
}
The format of the called function is:
Functionname param1 param2 ......

Shell functions can complete some routine work and have their own exit States. Therefore, functions can also be used as conditions for control structures such as if and while.

Parameters are not required for function definition, but can be included when a function is called. In this case, shell will assign these parameters to the corresponding location parameters $1, $2 ,... and $ *.

8) Command Group

There are two command grouping methods in shell: "()" and "{}". The former creates a new sub-process when the shell executes the commands in, then the sub-process executes the commands in the circular arc. When a user does not want to change the status set (such as location parameters, environment variables, and current working directory) during command execution to affect the execution of the following statements, these commands should be placed in the circular arc so that all changes can only affect sub-processes without any interference from the parent process; {} is used to use the output results of the commands executed in sequence for the input (pipe mode) of another command ). When we really want to use circular arc and curly arc (such as calculating the expression priority), we need to add an escape character before it (/) so that the shell knows that they are not used for command execution control.

9) Signal

The trap command is used to capture signals in the shell program. There are three methods to respond to these signals:

(1) execute a program to process this signal.
(2) default operation for receiving signals
(3) Ignore this signal

Trap provides three basic forms for the above three methods:

The first form of Trap Command will execute the command string in double quotation marks when shell receives signals with the same values in the signal list.

Trap "commands" signal-list
Trap "commands" signal-list

To restore the default signal, use the second form of trap command:
Trap signal-list

The third form of trap command allows ignoring signals:
Trap "" signal-list

Note:

(1) The signal 11 (segment violation) cannot be captured, because the shell itself needs to capture the signal for memory dump.
(2) In the trap, you can define the processing of the signal 0 (in fact, there is no such signal). The shell program sends this signal when it terminates (such as executing the exit Statement.
(3) After capturing the signal specified in the signal-list and executing the corresponding commands, if these commands do not terminate the shell program, the shell program will continue to execute the command after the command received when the signal is received, which will easily cause the shell program to be unable to terminate.

In the trap statement, single quotes and double quotation marks are different. When the shell program first encounters a trap statement, it will scan the commands in commands. If commands is enclosed in single quotes, shell will not replace the variables and commands in commands. Otherwise, the variables and commands in commands will be replaced with the specific values at that time.

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.