Efficient Shell-Shell special character Summarization in Linux

Source: Internet
Author: User

Efficient Shell-Shell special character Summarization in Linux

In Linux, shell commands are used in any case. In actual use of Shell, it is easy to get started with programming experience, but it is slightly difficult to use the symbols in shell, when writing Shell scripts with various special symbols, if we can use them well, we can often get twice the result with half the effort, some symbol descriptions in Shell are listed as comparison tables for quick search. Let's see what Shell Symbols do you know in the following table?

Shell symbols and various explanations:

Shell symbol Usage and description
#

Annotation symbol (Hashmark [Comments])

1. Mark the line at the beginning of the shell file as shebang ,#! /Bin/bash;

2. Use it as a comment elsewhere. In a line, # the following content will not be executed unless;

3. When enclosed by single or double quotation marks, the # character itself does not have a comment.

;

Command separator [semicolon].

When multiple statements are to be placed in the same row, they can be separated by semicolons. Note: Sometimes semicolons must be escaped.

;;

Consecutive semicolons (Terminator [double semicolon]).

When the case option is used, it serves as the terminator for each option. When Bash version 4 + is used, you can also use [; &], [; &]

.

Dot command [period].

1. equivalent to the bash built-in command source, such:

  1. #!/bin/bash
  2. . data-file
  3. # Contains data-file;

2. As a part of the file name, at the beginning of the file name, it indicates that the file is hidden, and ls is generally not displayed (ls-a can be displayed );

3. As the directory name, one vertex represents the current directory, and two dots represent the upper directory (parent directory of the current directory ). Note that more than two vertices do not appear unless you enclose them with quotation marks (single/double) as the dot character itself;

4. In a regular expression, the dot represents any character.

"

Double quotation marks (partial quoting [double quote]).

Partial references. The content enclosed by double quotation marks can be expanded by variables or escape characters. If the double quotation marks appear in the string, they must be escaped. Therefore, the double quotation marks are not necessarily paired.

'

Single quotes (full quoting [single quote]).

The content enclosed by single quotes is regarded as a single string. variable extension is prohibited in single quotes. All characters are processed as characters (except single quotes). Single quotes must appear in pairs.

,

Comma (comma operator [comma]).

1. Used to connect a series of mathematical expressions. These mathematical expressions are evaluated, but only the last result is returned. For example:

  1. #!/bin/bash
  2. let t1=((a=5+1, b=7+2))
  3. echo t1=$t1, a=$a, b=$b
  4. # This $ t1 = $ B;

2. It is used in parameter substitution to indicate the lower-case letters. If there are two commas, it means all lower-case letters. Note that this feature was added during bash version 4. Example:

  1. a="ATest"
  2. echo ${a,}
  3. echo ${a,,}
  4. # Output aTest, followed by atest.
\

Backlash (escape [backslash]).

1. Before a special symbol, the function of escaping a special symbol only represents the special symbol itself, which is often used in strings;

2. put it at the very end of a line of command, indicating that the next carriage return is invalid (in fact, the Enter is escaped), and the input of the next new line is still part of the current command.

/

Slash, Diagonal Bar (Filename path separator [forward slash]).

1. As the path separator, only one oblique rod in the path represents the root directory, and the path starting with the oblique rod represents the path starting from the root directory;

2. represents the division symbol when used as an operator. For example:a=4/2

`

Backquotes (Command substitution [backquotes]).

Command replacement. This quotation mark is surrounded by commands. You can execute the surrounded command and assign the execution result to the variable. For example:a=`dirname '/tmp/x.log'`. The result returned by dirname is assigned to a. Note that here, Mitchell uses backquotes and single quotes. Note the difference.

:

Colon (null command [colon]).

Empty command. This command does not do anything, but has a return value. The return value is 0 (that is, true ). The role of this command is amazing.

1. can be used as a condition for the while endless loop;

2. Act as a placeholder in the if Branch (that is, when a branch does nothing );

3. Place it in a place where two yuan of operation is required as a separator, for example:: ${username=`whoami`}

4. assign a value to the string variable in parameter replacement. In the redirection operation (>), the length of a file is truncated to 0 (:> in this case, the target will not do anything ), this can only be used in common files, but not in pipelines, symbolic links, and other special files;

5. You can even use it for comments (# The post content will not be checked, but: The post content will be checked. If a statement has a syntax error, an error will be reported );

6. You can also use it as a domain separator, for example, in the environment variable $ PATH or passwd, there is a colon as a domain separator;

7. You can also use the colon as the function name, but this will change the original meaning of the colon (if you accidentally use it as the function name, you can useunset -f : To cancel the function definition ).

!

Exclamation point (reverse (or negate) [bang], [exclamation mark]).

Returns a test result or exits.

1. indicates the anti-logic, such as the following! =, Which indicates not equal;

2. Return the inverse, for example, ls [! 0-9] # indicates that a is not followed by a number;

3. In different environments, exclamation points can also appear in indirect variable references;

4. In the command line, it can be used for calling the historical command mechanism. You can try it! $ ,! #, Or! -3. Note that this feature cannot be used (disabled) in script files ).

*

Asterisk (wildcard/arithmetic operator [asterisk]).

1. As a wildcard matching the extension of the file name, it can automatically match every file in the given directory;

2. Regular Expressions can be used as character delimiters, indicating that the matching rules match any time before them;

3. Multiplication is represented in arithmetic operations.

**

Double Star (double asterisk ). Represents a power operation in arithmetic operations.

?

Question mark (test operator/wildcard [Question mark]).

1. Conditional Testing;

2. represents the C-style ternary operator (condition? True-result: false-result ));

3. The parameter replacement expression is used to test whether a variable has a set value;

4. As a wildcard, it is used to match a single character in the extension feature of the file name;

5. In a regular expression, it indicates that the regular expression matches the previous rule 0 times or 1 time.

$

Dollar sign (Variable substitution [Dollar sign]).

1. As the prefix of a variable, replace it with a variable, that is, reference the content of a variable, for example:echo $PATH;

2. The regular expression is defined as the End of line ).

${}

Variable substitution ).

Represents a variable in a string.

$‘...’

Expand the reference content and execute the escape content in single quotes (the single quotes are originally referenced as is). This method will escape one or more [\] after the single quotes, the hexadecimal value is expanded to ASCII or Unicode characters.

$*

$@

Positional Parameters ).

This is used when passing parameters when using a script file. Both return all parameters of the script file, but $ * returns all parameters as a whole (string), and $ @ returns a list of parameters as a unit. Note that you must use double quotation marks to enclose $ *, $. These two variables are affected by $ IFS. Some details should be taken into account in actual application.

$#

Indicates the number of parameters passed to the script.

$?

When this variable value is used, the return value is the exit status code of the last command, function, or script. If there is no error, it is 0, for example, it is not 0, it indicates that there was an error in the last execution before this.

$$

Process ID variable, which saves the process ID value for running the current script.

()

Parentheses (parentheses ).

1. Command group ). Commands enclosed by parentheses are command groups. commands in the Command Group are actually executed in subshell. Because it is run in the sub-shell, there is no way to get the value of the variable in the brackets outside, but in turn, the Command Group can get the value outside, this is a bit like the relationship between local variables and global variables. In practice, if you want to perform the cd-to-subdirectory operation and return it to the current directory after the operation is complete, subshell can be used for processing;

2. Used for Array initialization.

{x,y,z,...}

Brace Expansion ).

This extension can be used in the command to expand the parameter list. The command will perform matching extension according to the mode separated by parentheses in the list. Note that no space exists in the extension of curly brackets. If spaces are necessary, they must be escaped or referenced using quotation marks. Example:echo {a,b,c}-{\ d," e",' f'}

{a..z}

Added the extension of curly braces in Bash version 3. You can use {.. z} represents the list of all characters in the A-Z, this method of extension Mitchell tested, as if only for the A-Z, a-z, and number {Min .. maximum.

{}

Code block (curly brackets ).

This is an anonymous function, but unlike the function, the variables in the code block can still be accessed after the code block. Note: There must be spaces on the inside of the curly braces to separate them with statements. In additionxargs -iCan also be used as a placeholder for text to mark the position of the output text.

{} \;

This {} indicates the path name, which is not built-in by shell. As you can see, it seems that it is only used in the find command. Pay attention to the semicolon next to it. This is the endfindCommand-execIn actual use, escape the command sequence to avoid shell errors.

[]

Brackets ).

1. indicates that the Shell will test the expressions in []. Note that [] is part of the Shell built-in test, rather than using external commands./usr/bin/test;

2. In the context of the array, it indicates the array element. Fill in square brackets with the position of the array element to get the corresponding content, such:

  1. Array[1]=xxx
  2. echo ${Array[1]};

3. It indicates the range of the character set. In the positive expression, square brackets indicate the range of character sets that can match the position.

[[]]

Double brackets ).

This structure is also a test to test the expressions in [] (Shell keywords ). This is better than single brackets to prevent logical errors in the script, such as: &, ||,<,> the operator can be tested in, but it cannot pass in. [[] Does not contain filename expansion or Word splitting, but it can be replaced with Parameter expansion and command substitution ). You do not need to use file name wildcards or separators such as white spaces. NOTE: If octal and hexadecimal are displayed, shell automatically performs conversion and comparison.

$[...]

Integer expansion ).

Execute an integer expression in square brackets. Example:

  1. a=3
  2. b=7
  3. echo $[$a+$b]
  4. echo $[$a*$b]
  5. # Returns 10 and 21
(())

Double parentheses ).

Integer expansion ). The function is similar to the above $ [], but note that $ [] returns the value of the expression in it, while () is only executed and does not return a value. If the variable value changes after the two operations, the subsequent code will be affected. You can assign values to variables. You can perform one-to-one Operations on variables, or two-to-one or three-object operators.

>

&<

>&

>>

<

<>

Redirection ).

scriptname >filenameRedirects the output of scriptname to the file filename. If the file exists, it overwrites it;

command &>filenameRedirects the standard output (stdout) and standard error (stderr) of the command to the file filename;

command >&2Redirects the standard output (stdout) of command to the standard error (stderr;

scriptname >>filenameAppend the scriptname output (same as>) to the filenmae file. If the file does not exist, create it.

[i]<>filenameOpen the filename file for reading or writing, and specify "I" as the file descriptor for the file. If the file does not exist, it will be created.

(command)>

<(command)

This is Process Substitution ).

Note that there must be no space between parentheses and <,>. Otherwise, an error is returned. It works a bit like a channel, but it is somewhat different from the pipeline in usage. The pipeline is run as a sub-process. This command will/dev/fd/Similar/dev/fd/63,/dev/fd/62These temporary files are used to transmit data.

Mitchell personally guessed that this method was used for transmission because the first and second processes do not belong to the same process, therefore, we need to use shared files to transmit data (in this case, the pipeline should also have the same file ?). Some people on the Internet say that this is just a shared file, but after testing, although there are/dev/fd/63This file is generated, but it is actually a link to pipe: [43434.

<<

Double less than sign (here-document [double less then marks]).

This is also called Here-document, which is used to redirect subsequent content to the stdin of the left-side command. <This reduces the formatting time and makes it easier to execute commands. You only need to enter the <and terminator in the implementation, and then (usually after the carriage return) You can enter any content, as long as you enter the terminator in the last new line, the data can be imported. When using here-document, you can retain spaces, line breaks, and so on. To make the shell script more clean, you can place a hyphen (-) between <and terminator (-).

<<<

Here-strings ). The Here-string is similar to the Here-document Syntax:command [args] <<<["]$word["]; $ Word is the stdin of command.

<

>

Smaller than, greater than (ASCII Comparison ).

ASCII comparison, which is the ASCII comparison of variables, String? Number? Er... isn't this ASCII comparison?

\<...\>

Word boundary ).

This is a special delimiter used in regular expressions to mark the word boundary. For example, the will match there, another, them, etc. If you only want to match the, you can use this word mark, \ <the \> can only match.

|

Pipeline (pipe ). Pipelines are concepts of Linux and Unix, which are very basic and important. It serves to use the output (stdout) generated by the command before (left) in the pipeline as the input (stdin) of the command after (right) in the pipeline ). For example:ls | wc l, You can connect commands together using pipelines. Note: The standard output of each process is used as the standard input for the next command. The standard output during this period cannot span the pipeline as the standard input for subsequent commands, for example:cat filename | ls -al | sort. Think about the output? At the same time, the pipeline is run by sub-processes, so the pipeline cannot cause variable changes.

>|

Force redirection ).

This forces the rewriting of existing files.

&

And (Run job in background [ampersand]).

If the command is followed by an & symbol, this command will be run in the background. Sometimes, a command running in the script in the background may cause the script to be suspended and waiting for input. This situation can be solved by using the wait command after the original script.

&&

||

Logical operator ).

In the test structure, the two operators can be used to connect two logical values. | Returns 0 (true) If one of the test conditions is true, false if all false is false, and 0 if both test conditions are true ), false indicates false.

-

Minus signs and hyphens (Hyphen/minus/dash ).

1. as an option, the prefix [option, prefix] is used. The option flag used for the command or filter; the prefix of the operator. For example:

  1. # COMMAND-[Option List]
  2. ls -al
  3. sort -dfu $file
  4. set-- $variable
  5. if[ $file -ot $file2 ]
  6. then
  7. echo "$file is older than $file2."
  8. fi

2. Source or target [dash] For stdin or stdout redirection. When tar does not have a bunzip2 program patch, we can do this:bunzip2 linux-2.6.13.tar.bz2 | tar xvf - . Use the extracted data as the standard tar input (a-representation is used here)

Note: If the object name starts with [-] during actual execution, an error may occur when this operator is added as a targeted operator, in this case, you should add a proper prefix path to the file to avoid this situation. Similarly, when echo is a variable, if the variable starts, unexpected results may also occur. For the sake of insurance, you can use double quotation marks to reference scalar:

  1. var="-n"
  2. echo $var
  3. # What is the output?

Also, this representation method is not built in Bash. To achieve this effect, you need to check whether your software supports this operation;

3. previous working directory. Therefore, if you want to change the cd path to another directory, you can use cd-. In fact, here [-] uses the $ OLDPWD of the environment variable. Note: [-] Here is different from the previous one;

4. Minus or minus signs used in arithmetic operations.

=

Equal sign (Equals ).

1. assign values to variables. Do you have spaces on both sides of the equal sign;

2. It appears as a comparison character in the comparison test. Note that if it appears as a comparison character in brackets, there must be a space character on both sides of the equal sign.

+

Plus sign (Plus ).

1. Arithmetic Operator, indicating addition;

2. In a regular expression, it indicates that the matching rule is matched at least once;

3. Mark the options in the command or filter, use + in some commands or built-in commands to enable some options, and use-to disable;

4. In parameter substitution (parameter substitution), + prefix indicates the substitution value (when the variable is empty, + is followed by the value)

%

Percent sign (modulo [percent sign]).

1. In arithmetic operations, this is a modulo operator, that is, the remainder of two numbers after division;

2. In parameter substitution, it can be used as a pattern match. Example:

  1. p=b*9
  2. var="abcd12345abc479"
  3. echo ${var%p}, ${var%%p}
  4. # Search from the right (think about the symbol from the left ?)
  5. # Any content between B and 9 (inclusive)
  6. # First, find the shortest matching item
  7. # Find the largest matching item (Greedy match ?)
~

Wave Number (Home directory [tilde]).

This is the same as the internal variable $ HOME. The default value is the Home Directory (main directory) of the current user ~ /The effect is consistent. If the Tilde is followed by the user name, it indicates that it is the Home Directory of the user.

~+

The current working directory ).

This is the same as the built-in variable $ PWD.

~-

Previous working directory ).

This is consistent with the internal variable $ OLDPWD, and the previous [-] is the same.

=~

Bash Version 3 has been introduced. This is a regular expression matching. Available in [[] testing, for example:

  1. var="this is a test message."
  2. [["$var"=~ tf*message ]]&& echo "Sir. Found that."|| echo "Sorry Sir. No match be found."
  3. # You can modify the regular expression match in the middle. The regular expression can be enclosed in double quotation marks, but not necessarily.
^

Caret ).

1. In a regular expression, it is used as the position marker of the first row (beginning-of-line;

2. In Parameter substitution (Parameter substitution), there are two ways to use this function: One delimiters (${var^}), Or two (${var^^}(Bash version> = 4 ).

Blank

Whitespace ).

A blank space character is not only a space character, but also a Tab character (tabs), a blank line (blank lines), or a combination of these two types. It can be used as a function separator to separate commands or variables. Empty rows do not affect script behavior. Therefore, you can use it to plan script code to increase readability, the built-in special variable $ IFS can be used to separate input parameters for certain commands. By default, it is a blank character. If there is a blank character in a string or variable, you can use quotation marks to avoid possible errors.

How much do you know? At the beginning of the Shell script, Mitchell found that many of them did not know each other.

Note: Due to translation, the content in this article may not be completely accurate. If you find any error, please forgive me for correction.

Refer:

  1. Source of this article: Advanced Bash-Scripting Guide
  2. Dialog UNIX :! $ # @ * %
  3. Here document of wikipedia

This document provides me with a lot of help for Mitchell. I would like to thank their authors for their selfless contributions!

This article permanently updates the link address:

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.