Shell basic syntax

Source: Internet
Author: User
Tags echo command
Shell basic syntax

Basic shell Syntax:
Like advanced programming languages, shell also provides instructions and functions for using variables.
For shell, the value of all variables is a string, and the shell program uses $ VaR
Reference the value of a variable named var.

Shell has the following basic types of variables:
(1) environment variables defined by shell:
At the beginning of the execution, shell has defined some related to the operating environment of the system.
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 will
And find the first executable with the same command name.
The file 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
Usage changes.
PS1: Primary prompt. under privileged users, the default primary prompt is #.
The default primary prompt is $.
PS2: When the shell receives the user's input command, if the user
Enter '\' At the end of the input and press enter, or when the user presses the Enter key, shell determines that the user is lost.
When the input command is not completed, this auxiliary prompt is displayed, prompting the user to continue entering the command
The default secondary 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.
$ Should be added before the variable name when the variable content is added; when assigning values to the variable, the equal signs must not be on either side
Space can be left. If the variable itself contains space, the entire string must be enclosed by double quotation marks.
When writing a shell program, we recommend that all
All variable names are represented by uppercase letters.
Sometimes when we want to describe a variable and set it to a specific value
When changing its value, you can use the following command to ensure the read-only performance of a variable:
Readonly variable name
At any time, the created variable is only the local variable of the Current Shell, so it cannot
It is used by other commands or Shell programs run by shell, and the Export command can
Local variables are provided 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
The variables described in export can be used in all commands or programs run after shell.
To access.
You can use unset to clear variable values in the following format:
Unset variable name

(3) location parameters:
Location parameters are determined based on their respective locations in the command line that calls the shell program.
Fixed variables are the parameters entered after the program name. location parameters are separated by spaces,
Shell replaces $1 in the program file with the parameter at the first position, replaces $2 with the second, and Class
Push. $0 is a special variable whose content is the file name of the current shell program,
Therefore, $0 is not a positional parameter and is not included when displaying all current positional parameters.

(4) predefined variables:
Predefined variables are similar to environment variables and are defined at the beginning of shell.
The difference is that you can only use these variables according to shell definitions, instead
Can be redefined. All predefined variables are composed of the $ operator and another symbol, commonly used
Shell pre-defined variables include:
$ # Number of location parameters.
$ * Content of all location parameters.
$? Status returned after the command is executed.
$ Process ID of the current process.
$! The last process number that runs in the background.
$0 indicates the name of the currently executed process.
$? Used to check whether the previous command is correctly executed. (in Linux, the command exits.
If the status is 0, the command is correctly executed. If the value is not 0, an error occurs .)
$ The most common purpose of a variable is to use the name of the temporary file to ensure that the temporary file is not
Will be repeated.

(5) variable for parameter replacement:
Shell provides the parameter replacement function so that users can change the parameters according to different conditions.
Assign different values. There are four types of variables for parameter substitution. These variables are usually the same as a location parameter.
Determines the value of a variable based on whether the specified location parameter has been set.
Their syntax and functions are as follows.
A. Variable =$ {parameter-word}: If a parameter is set, replace it with the parameter value
Otherwise, replace the variable with the word. That is, the value of this variable is equal to the value of a parameter, as shown in
If this parameter is not set, the variable is equal to the word value.
B. Variable =$ {parameter = word}: If a parameter is set, replace it with the parameter value
Otherwise, set the variable to word and replace the parameter value with word.
Location parameters cannot be used in this way, because location parameters cannot be assigned in Shell programs.
C. Variable =$ {parameter? Word}: If a parameter is set, replace it with the parameter value.
Otherwise, the word is displayed and exited from the shell. If the word is omitted
Standard information. This variable must be equal to the value of a parameter.
To display a message and exit. Therefore, this method is often used to indicate errors.
D. Variable =$ {parameter + word}: If a parameter is set, replace the variable with word,
Otherwise, no replacement is performed.
The "parameter" in all four forms can be either a location parameter or another variable
Quantity, but there are many situations where location parameters are used.

Process Control for shell program design:
Like other advanced programming languages, shell provides the ability to control program execution streams.
Command, including the condition branch and loop structure. You can use these commands to create
Complex programs.
Unlike traditional languages, shell is not a Boolean algorithm used to specify the condition value,
Commands and strings.

1. Test command
The test command is used to check whether a condition is true. It can be used for values, characters, and
The test characters and corresponding functions are as follows:
(1) numerical test:
-True if EQ is equal
-True if ne is not equal
-True if the value of-GT is greater
-If Ge is greater than or equal to, it is true.
-Lt is true if it is less
-If the value of-Le is less than or equal to, it is true.

(2) string test:
= Equals to true
! = Not equal to true
-Z string determines whether the string is null
-N indicates whether the string is not null.

(3) file test:
-E: the file name is 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. If the file exists and contains at least one character, it is true.
-D. The file name is true if the file exists and is a directory.
-F. The file name is true if the file exists and is a normal file.
-C file name: if the file exists and is a special character file, it is true.
-B. The file name is true if the file exists and is a special file.

In addition, Linux also provides (!), Or (-O), non-(-a) three logical operations
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]
For 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. Its general format is
If condition command string
Command string when the condition is true
Command string when the condition is false

3. For Loop
The for loop executes a command sequence for all possible values of a variable and assigns
Several values can be provided in the program in the form of a numerical list, or outside the program
The general format of the. For loop provided in the form of location parameters is:

For variable name [in Value List]
Several command lines
The variable name can be any string selected by the user. If the variable name is Var
The value given later replaces $ VaR in the cyclic command list with the value in sequence. If in is omitted
The value of the variable VAR will be the location parameter. Do will be executed for every possible value assignment of the Variable
And done.

4. While and until Loops
The while and until commands both use the return status value of the command to control the loop. While
The general cycle format is:
Several command lines 1
Several command lines 2
If the return status of the last command in "Several command line 1" in while is true,
While the loop continues to execute "Several command lines 2" between do... done ".

The until command is another type of loop structure, which is similar to the while command. Its format is as follows:
Several command lines 1
Several command lines 2

The difference between an until loop and a while loop is that a while loop follows a true condition
Continued execution loop, while until continues execution loop when the condition is false.
Shell also provides the "true" and "false" commands to create an infinite loop structure.
Their return status is always 0 or total is not 0.

5. Select case conditions
The IF Condition Statement is used to select one of the two options, and the case condition is selected as the user
You can select one option from multiple options based on the value of a string or variable. The format is as follows:
Case string in
Several command lines 1
Several command lines 2
Other command lines

Shell calculates the value of the string, and runs the result in sequence and the formula exp-1,
Exp-2 and so on until a matching formula is found.
, Then execute the following command until a pair of semicolons (;) is encountered.
You can also use the shell wildcard ("*","? "," [] ").
* Is usually used as the final formula of the Case command so that no matching match can be found before.
Execute the "other command line" command for configuration items.

6. Unconditional control statements break and continue
Break is used to terminate the execution of the current loop immediately, while contiune is used to not execute the loop
And immediately start the execution of the next loop.
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 the shell program form, the difference is that it is not a single
It is a part of the shell program. The basic format defined by the function is:
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 records.
So the function can also be used as a condition for the IF, while and other control structures.
Parameter descriptions are not required for function definition, but parameters can be included when a function is called,
At this time, 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 ().
The sub-process executes commands in the Circular Arc. When you execute a command, you do not want
To set the running status (such as location parameters, environment variables, and current working directory)
When the changes affect the execution of the following statements, these commands should be placed in the circular arc.
In this way, we can ensure that all changes only affect sub-processes, and the parent process is not disturbed.
{} Is used to input the output results of the commands executed in sequence
Method ).
When we really want to use circular arc and curly arc (for example, computing formula priority)
You need to add an escape character (\) before it to let the shell know that they are not used for Command Execution
Used for row control.

9. Signal
The trap command is used to capture signals in Shell programs. There are three response methods:
(1) execute a program to process this signal.
(2) receive the default signal operation.
(3) Ignore this signal.
Trap provides three basic forms for the above three methods:
The first form of Trap Command in Shell received the value in the signal list
When the signal is the same, the command string in double quotation marks will be executed.
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 the trap command allows the ignore signal:
Trap "" signal-list
(1) cannot capture the signal 11 (segment violation), because the shell itself needs to capture the signal
To dump the memory.
(2) The processing of signal 0 can be defined in trap (this signal is not actually used ),
The shell program sends this signal when it terminates (such as executing the exit Statement.
(3) capture the signal specified in the signal-list and execute the corresponding command
If these commands do not terminate the shell program, the shell program will continue to execute
The command after the Command executed when receiving the signal, which will easily lead to the shell program
Cannot be terminated.
In addition, in trap statements, single quotes and double quotes are different. When the shell program
When a trap statement is first encountered, the command in commands is scanned. If
If commands is enclosed in single quotes, shell will not
And command. Otherwise, the variables and commands in commands will use the specific values at that time.

How to run the shell program:
You can use any editing program to write a shell program.
So it does not need to be compiled into the target program. According to the shell programming convention
Bash is used as an example. The first line of the program is generally "#! /Bin/bash ", where # indicates that this row is a note
Release, exclamation point! Tell Shell to run the command after the exclamation mark and use the rest of the document as the input
Run/bin/bash and run/bin/Bash to execute the contents of the shell program.

There are three methods to execute the shell program:
1. sh shell program file name
The command format for this method is:
BASH Shell program file name
This is actually to call a new bash command to explain the program, and put the shell program file
Name is passed to it as a parameter. The newly started shell will read the specified file, Executable File
When all commands are executed, the method ends. The advantage of this method is that
Use the shell debugging function.

2. Sh
Bash <shell program name
In this way, the shell command interpreter's input is taken from
The specified program file.

3. Run the CHMOD command to make the shell program executable.
Whether a file can run depends on whether the file content is executable and the file has
Execution right. For Shell programs, when a file is generated using the editor
The permission is 644 (RW-r --). Therefore, when you need to run this file, you only need
Directly type the file name.

Among the three methods for running Shell programs, it is best to choose the following method:
When you create a shell program that is not sure about its correctness, you should use the first method.
When a shell program has been debugged, use the third method to debug it.
Fixed, you only need to enter the corresponding file name and can be called by another program.

4. Bash program debugging
Errors are inevitable in the programming process. Sometimes, debugging is more costly than programming.
More time, the same is true for Shell programs.
Shell program debugging mainly uses bash commands to explain the program selection items. Call
Bash-select the shell program file name
Several common options are:
-E. Exit immediately if a command fails.
-N reads commands but does not execute them
-During U replacement, unset variables are considered as errors.
-V display them when reading shell input rows
-X displays commands and their parameters when executing commands.
All the above options can also be used in the shell program in the form of "Set-select item"
And "set + select item" will disable this option. If you only want
When a part uses some selection items, You can enclose this part with the preceding two statements.

(1) unset variable exit and exit now
The unset exit feature allows you to check all variables.
Unassigned variables terminate shell program execution. Shell usually allows unassigned variables
In this case, the value of the variable is null.
Once the unspecified variable is used, the error message is displayed and the program running is terminated.
Set the variable exit option to-U.
When the shell is running, if a command does not exist or cannot be executed, the redirection fails or
If the command ends abnormally, the error message is displayed in
On the terminal screen, the shell program will continue to execute. To force the program when an error occurs
The shell program ends immediately. You can use the-e option to terminate the execution of the shell program immediately.

(2) SHELL Program tracking
The main method to debug a shell program is to use shell commands to explain the program's-V or-x selection.
Item to track program execution.-V select the item so that shell can read it during program execution.
Each command line is displayed, and the-x option enables shell to execute the program.
To display each of the commands it executes with a + command name at the beginning of the line.
A variable and the value obtained from the variable are also displayed. Therefore, the main difference between them is:
If no-V exists before the command line is executed, the original content of the command line is displayed.
The contents of the replaced command line are displayed.
In addition to shell-V and-x options, you can also use
Take some auxiliary debugging measures. For example, it can be used in some key aspects of the shell program.
The echo command shows the necessary information. It serves as the printf language in C language.
In this way, you can know where the program runs and the current state of the program.

Bash Internal commands:
The bash command explains that the package contains some internal commands. The internal commands are listed in the directory column.
Tables are invisible. They are provided by the shell itself. Common internal Commands include echo,
Eval, exec, export, readonly, read, shift, wait, and point (.).
This section briefly introduces the Command Format and functions.

1. Echo
Command Format: Echo ARG
Function: displays the string specified by Arg on the screen.

2. Eval
Command Format: eval ARGs
Function: When the shell program runs the eval statement, the shell reads The args parameter and
They are combined into a new command and then executed.

3. Exec
Command Format: exec Command Parameters
Function: When the shell executes the exec statement, it does not create a new sub-process
Run the specified command.
The original shell) is terminated, so
The statement will no longer be executed.

4. Export
Command Format: Export variable name or: Export variable name = variable value
Function: shell can use export to bring its variables down to the sub-shell, thus
Let the child process inherit the environment variables in the parent process. However, the Child shell cannot use
Export brings its variables up to the parent shell.
Note: The export statement without any variable name will display all the current
Export variable.

5. readonly
Command Format: readonly variable name
Function: identifies a user-defined shell variable as unchangeable without any parameters.
The readonly command of the number displays all read-only shell variables.

6. Read
Command Format: Read variable table
Function: reads a row from a standard input device, splits it into several words, and assigns a value to shell.
Variable defined in the program.

7. Shift statement
Function: The Shift statement renames all location parameter variables as follows,
That is, $2 becomes $1, $3 becomes $2...
Make all the location parameters move one position to the left, and
Set the parameter $ # Minus 1 until it is reduced to 0.

8. Wait
Function: enables shell to wait for all sub-processes started in the background to end. Wait returns
The value is always true.

9. Exit
Function: exit the shell program. You can specify a number after exit.
Is returned.

10. "." (point)
Command Format:. shell program file name
Function: enables shell to read the specified shell program file and execute
All statements.
11. unset
Command Format: unset [-FV] [variable or function name]
Function: delete a variable or function.
Parameter:-F: only deletes a function.
-V: only delete variables

12. grep: G (globally) Search for a RE (regular
Expression) and P (print) the results.
Command Format: grep [Option]... pattern [file]...
Parameter:-I: case-insensitive
-C: print the number of matched rows.
-L: searches for matching items from multiple files.
-V: searches for rows that do not contain matching items.
-N: print the rows and Row labels containing matching items.
Re (Regular Expression ):
\ Ignore the original meaning of special characters in Regular Expressions
^ Match the starting line of the Regular Expression
$ Match the end row of the Regular Expression
\ <Starts from the row that matches the Regular Expression
\> Ends with the row matching the Regular Expression
[] A single character. For example, [a] means that a meets the requirements.
[-] Range; for example, [A-Z] That is a, B, c Until Z all meet the requirements
. All single characters
* All characters. The length can be 0.
Result: The content of the matched row is printed.

13. Cut
Command Format: Cut [Option]... [file]...
Parameter:-D ''specifies the domain Separator
-C the num1-num2 shows each line starting from num1 to num2
-F m-N: displays the domain m to the domain N (the default tab is the domain score ).
Delimiter ).
Function: displays the text of each row starting with num1 to num2.

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: 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.