Wildcards, special symbols, and file descriptors in Shell

Source: Internet
Author: User

I. wildcard characters

* Represents any character ranging from 0 to infinite.

Example: Find the file name starting with cron under/etc/

[Root @ instructor Desktop] # ls/etc/cron *

/Etc/cron. deny/etc/crontab

/Etc/cron. d:

0 hourly raid-check sa-update sysstat

/Etc/cron. daily:

00 webalizer cups makewhatis. cron prelink rhsmd

Certwatch logrotate mlocate. cron readahead. cron tmpwatch

/Etc/cron. hourly:

0 anacron

/Etc/cron. monthly:

Readahead-monthly.cron

/Etc/cron. weekly:

? Represents any character of "must have one"

Example: Find the file name under/etc/That is exactly five letters

[Root @ instructor Desktop] # ls/etc /????? <-------------- Due? There must be one, so five? That's right.

/Etc/fstab/etc/hosts/etc/magic/etc/vimrc

/Etc/group/etc/issue/etc/rwtab

/Etc/audit:

Auditd. conf audit. rules

.......... The result is displayed in the omitted part ..........

[] Also represents the character "must be in parentheses" (not any character ). For example, [abcd] indicates "There must be one character, which may be a, B, c, d 』

Example: Find the file name starting with a lowercase letter under/etc:

[Root @ instructor Desktop] # ll-d/etc/[a-z] *

Drwxr-xr-x. 3 root 4096 Apr 22 2013/etc/abrt

Drwxr-xr-x. 4 root 4096 Apr 22 2013/etc/acpi

-Rw-r --. 1 root 47 Apr 1523:36/etc/adjtime

-Rw-r --. 1 root 1512 Jan 12 2010/etc/aliases

-Rw-r --. 1 root 12288 Apr 22 2013/etc/aliases. db

Drwxr-xr-x. 2 root 4096 Apr 22 2013/etc/alsa

Drwxr-xr-x. 2 root 4096 Apr 22 2013/etc/alternatives

-Rw-r --. 1 root 541 Mar 4 2011/etc/anacrontab

.......... The result is displayed in the omitted part .........

[-] If there is a minus sign in brackets, it indicates "All characters in the encoding sequence 』. For example, [0-9] indicates all numbers between 0 and 9, because the numbers are encoded consecutively!

Example: Find the file name under/etc/that contains numbers

[Root @ instructor Desktop] # ls/etc/* [0-9] *

/Etc/DIR_COLORS.256color/etc/mke2fs. conf/etc/pnm2ppa. conf

/Etc/krb5.conf/etc/named. rfc1912.zones

/Etc/krb5.conf-gls/etc/pbm2ppa. conf

.......... The result is displayed in the omitted part ..........

[^] If the first character in the brackets is an exponential sign (^), it indicates "reverse selection". For example, [^ abc] indicates that there must be a character, as long as it is not, other characters of B and c are accepted.

Example: Find the file name starting with a non-lowercase letter under/etc:

[Root @ instructor Desktop] # ll-d/etc/[^ a-z] *

Ii. Summary of special symbols

Common special symbols in shell are listed as follows:

#;.,/\ 'String' |! $ {}$? $ * "String "***? : ^ $ # $ @ 'COMMAND '{} [] [[] () | & {xx, yy, zz ,...}~ ~ + ~ -& \ <... \> +-% =! =

# Comments)

This is almost a full-market symbol, except for the "first line" that has been previously mentioned"

#! /Bin/bash

A well number often appears at the beginning of a line or after a complete command. This type of situation indicates that the annotation text is followed by the symbol and will not be executed.

# This line is comments.

Echo "a = $ a" # a = 0

Because of this feature, when you do not want to execute a certain line of command temporarily, you only need to add # At the beginning of the line. This is often used in the writing process.

# Echo "a = $ a" # a = 0

If it is used in an instruction, enclosed in double quotation marks, or behind the inverted slash, it becomes a general symbol and does not have the special functions described above.

~ Home Directory of the account

It is a common symbol, representing the user's home directory: cd ~; You can also add the account name "cd ~" directly after the symbol ~ User

Or use it as a part of the path :~ /Bin ;~ + The current working directory. This symbol represents the current working directory. It serves the same purpose as the built-in command pwd.

# Echo ~ +/Var/log ~ -Last working directory. This symbol represents the last working directory.

# Echo ~ -/Etc/httpd/logs

; Semicolon (Command separator)

In shell, the symbol used for the "continuous command" function is "Semicolon ". For example, cd ~ /Backup; mkdir startup; cp ~ /. * Startup /.

; Consecutive semicolon (Terminator)

Dedicated to the case option, as the role of Terminator.

Case "$ fop" inhelp) echo "Usage: Command-help-version filename"; version) echo "version 0.1"; esac

. Comma (dot)

In shell, the user should be clear that a dot represents the current directory, and two dots represent the upper directory.

CDPATH = .:~ :/Home/web:/var:/usr/local

In the upstream CDPATH setting, dot after the equal sign represents the meaning of the current directory.

If the file name starts with "dot", the file is a special file, which is displayed only when the-a option is added to the ls command. In addition, in the regular expression, a dot represents matching a character.

'String' single quotes)

The content enclosed by single quotes is considered as a single string. The $ symbol representing the variable in quotation marks does not work. That is to say, it is treated as a general symbol to prevent replacement of any variable.

Heyyou = homeecho '$ heyyou' # We get $ heyyou

"String" double quotes)

The content enclosed by double quotation marks is considered as a single string. It prevents wildcard extension, but allows variable extension. This is different from how a single reference is processed.

Heyyou = homeecho "$ heyyou" # We get home

Backticks)

The preceding single double quotes enclose strings. What if the string is a command column? The answer is no execution. To handle this situation, we must use single quotes.

Fdv = 'date + % F' echo "Today $ fdv"

The date + % F in the inverted quotation marks is considered as an instruction, and the execution result is included in the fdv variable.

, Comma)

This symbol is often used in operations as a "segmentation" purpose. Example

#! /Bin/bashlet "t1 = (a = 5 + 3, B = 7-1, c = 15/3)" echo "t1 = $ t1, a = $, B = $ B"

/Forward (forward slash)

Indicates a directory in the path.

Cd/etc/rc. dcd.../. cd/

A single/usually represents the root directory. In the four arithmetic operations, it represents the division symbol.

Let "num1 = (a = 10/2, B = 25/5 ))"

\ Backslash ()

In interactive mode, the escape character has several functions; Before the instruction, the role of canceling aliases; before the special symbol, the role of the special symbol disappears; put it at the end of the command, indicating that the command is connected to the next line.

# Type rmrm is aliased to 'rm-I '# \ rm./*. log

In the above example, I added the escape character before the rm command to temporarily cancel the alias function and restore the rm command.

# Bkdir =/home # echo "Backup dir, \ $ bkdir = $ bkdir" Backup dir, $ bkdir =/home

In the previous echo example, \ $ bkdir and escape cancel the $ variable function. Therefore, $ bkdir is output, while the second $ bkdir outputs the variable content/home.

| Pipeline)

Pipeline is a basic and important concept of UNIX systems. Connect the standard output of the previous command as the standard input of the next command.

Who | wc-l

Making good use of this concept can help streamline scripts.

! Exclamation point (negate or reverse)

It usually indicates the anti-logic function, for example, in condition detection! = To indicate "not equal"

If ["$? "! = 0] thenecho "Executes error" exit 1fi

In the rule expression, she assumes the "anti-logic" role.

Ls [! 0-9]

In the preceding example, other files except a0, a1... a9 are displayed.

: Colon

In bash, This is a built-in command: "do nothing", but the returned status value is 0.

:

Echo $? # The response is 0.

:> F. $

The above line is equivalent to cat/dev/null> f. $. Not only is the statement short, but the execution efficiency is much higher.

Sometimes, the following usage occurs:

:$ {HOSTNAME ?} $ {USER ?} $ {MAIL ?}

This line is used to check whether these environment variables have been set. If they are not set, an error message is displayed as a standard error. Similar to test or if, this type of check can basically be processed, but it is not as concise and efficient as in the previous example.

In addition to the above, there is also a place where the colon must be used

PATH = $ PATH: $ HOME/fbin: $ HOME/fperl:/usr/local/mozilla

In the. bash_profile or any file with similar functions under the user's HOME directory, we use colons to set the "path" for segmentation.

? Question mark (wild card)

The role played on Filename expansion matches any character but does not contain null characters.

# Ls? A1

Make good use of her features to make more accurate file name matching.

* Asterisk (wild card)

Symbol. In Filename expansion, it represents any character and contains null characters.

# Ls a * a a1 access_log

During operation, it represents "multiplication ".

Let "fmult = 2*3"

In addition to the built-in command let, there is also an operation instruction expr, where the asterisk is also used as a "multiplication" role. However, be careful when using the escape character.

** Power Operation

The meaning of the two asterisks in the computing age.

Let "sus = 2 ** 3" echo "sus = $ sus" # sus = 8

$ Dollar sign)

Variable Substitution.

Vrs = 123 echo "vrs = $ vrs" # vrs = 123

In addition, it is defined as "end-of-line" in Regular Expressions ). This is often used in grep, sed, awk, and vim (vi.

Regular Expression of $ {} variable

Bash defines a lot of usage for $. The following table is from the online description

$ {Parameter:-word }$ {parameter: = word }$ {parameter :? Word }$ {parameter: + word }$ {parameter: offset: length }$ {! Prefix * }$ {# parameter }$ {parameter # word }$ {parameter % word }$ {parameter/pattern/ string }$ {parameter // pattern/string}

$ * Refers to the execution reference variable of the script. The algorithm of the referenced parameter is the same as that of the General Command. The command itself is 0, and the latter is 1, and so on. The reference variable is represented as follows:

$0, $1, $2, $3, $4, $5, $6, $7, $8, $9, ${10 }, ${11 }.....

For single-digit users, you can directly use a number. If the number is greater than two digits, you must use the {} symbol to enclose it.

$ * Indicates all symbols that reference variables. Double quotation marks must be added as needed.

Echo "$ *"

There is also a symbol with the same effect as $ *, but the utility and processing method are slightly different.

$ @

$ @ Has the same effect as $ *, but there is a difference between them.

Symbol $ * considers all referenced variables as a whole. But the symbol $ @ still retains the concept of block for each referenced variable.

$ #

This is also a symbol related to the referenced variable. Her role is to tell you the total number of referenced variables.

Echo "$ #"

$? Status variable)

Generally, UNIX (linux) processes end with the execution system calling exit. The return value is the status value. It is returned to the parent process to check the execution status of the child process.

If the command program is successfully executed, the return value is 0; If the command program fails, the return value is 1.

Tar cvfz dfbackup.tar.gz/home/user>/dev/nullecho "$? "$

Because the process ID is unique, it is impossible to have a repetitive PID at the same time. Sometimes, scripts need to generate temporary files to store necessary information. This script may also be used by users at the same time. In this case, the fixed file name is obviously unreliable in writing. Only dynamic file names can be generated. Symbol $ may meet this requirement. It represents the PID of the current shell.

Echo "$ HOSTNAME, $ USER, $ MAIL"> ftmp. $

Using it as a part of a file name can avoid overwriting of the same file name at the same time.

Ps: basically, the system recycles the executed PID and then allocates it as needed. Therefore, even if the temporary file is written using the dynamic file name, other problems may occur if the script is not cleared after execution.

() Command group)

Enclose a string of continuous commands in parentheses. This is called a command group for shell. Example: (cd ~ ; Vcgh = 'pwd'; echo $ vcgh), the Command Group has a feature, shell will generate subshell to execute this set of commands. Therefore, the variables defined in the variable only act on the Command Group itself. Let's look at an example.

# Cat ftmp-01 #! /Bin/basha = HCG (a = incg; echo-e "\ n $ a \ n") echo $ a #./ftmp-01incgfsh

In addition to the preceding Command Group, brackets are also used in the definition of array variables. They are also used in other scenarios where you may need to add escape characters, such as arithmetic expressions.

(())

Similar to let commands, these symbols are used in arithmetic operations and are built-in functions of bash. Therefore, the execution efficiency is much better than using the let Command.

#! /Bin/bash (a = 10) echo-e "in1_value, a = $ a \ n" (a ++) echo "after a ++, a = $"

{} Braces (Block of code)

Sometimes it appears in the script. the braces hold one or more segments ending with a semicolon to set the command or variable.

# Cat ftmp-02 #! /Bin/basha = hCG {a = inbc; echo-e "\ n $ a \ n"} echo $ a #./ftmp-02inbcinbc

This usage is very similar to the Command Group described above, but there is a difference that it is executed in the current shell and does not produce subshell.

Braces are also applied to the function. Broadly speaking, simply using braces only serves as a function without a specified name. Therefore, writing scripts in this way is quite good. This method can simplify the complexity of the script, especially for the output input.

In addition, braces have another usage:

{Xx, yy, zz ,...}

This combination of braces is often used in the combination of strings. Let's look at an example.

Mkdir {userA, userB, userC}-{home, bin, data}

We can obtain userA-home, userA-bin, userA-data, userB-home, userB-bin, userB-data, userC-home, userC-bin, userC-data, these directories. This set of symbols is widely applied. If you can make good use of it, the return is simplified and efficient. For example

Chown root/usr/{ucb/{ex, edit}, lib/{ex ?.? *, How_ex }}

If this is not supported, we have to repeat several rows several times!

[] Brackets

It often appears in the process control and plays a role in the implicit model. If ["$? "! = 0] thenecho "Executes error" exit 1fi

This symbol acts as a role in a regular expression similar to "range" or "set ".

Rm-r 200 [1234]

In the preceding example, it indicates deleting directories such as 2001,200 2 and 2003,200 4.

[[]

This group of symbols basically works the same as the previous [] symbols, but she allows them to directly use | and & logical symbols.

#! /Bin/bashread akif [[$ ak> 5 | $ ak <9] thenecho $ akfi

| Logical symbol

This will often be seen, representing the or logic symbol.

& Logical symbols

This also often shows the symbols representing the and logic.

& Background work

A single & symbol is placed at the end of the complete command column, which means that the command column is put into the background for work.

Tar cvfz data.tar.gz data>/dev/null &

\ <... \> Single-word boundary

These symbols are defined as "boundary" in Rule expressions. For example, if we want to find the word

Grep the FileA

You will find that words like there will also be considered as matching words. Because the coincidence is a part of there. If we want to avoid this situation, we need to add the "boundary" symbol.

Grep '\ 'filea

+ Plus sign (plus)

In the formula, it is used to represent "addition ".

Expr 1 + 2 + 3

In addition, it is used to represent the meaning of the first character of "many" in the Rule expression.

# Grep '10 \ + 9' fileb000010094259425931010009 # This symbol must be prefixed with the escape character.

-Dash)

In the formula, it is used to represent "subtraction ".

Expr 10-2

It is also the option symbol of the system command.

Ls-expr 10-2

In the GNU command, if the-symbol is used separately without the name of any file to be added, it indicates the meaning of "standard input. This is a common option for GNU commands. For example

Tar xpvf-

Here, the-symbol indicates reading data from standard input.

However, cd commands are quite special.

Cd-

This means to change the working directory to the "last" working directory.

% Division (Modulo)

In the formula, it is used to represent "division ".

Expr 10% 2

In addition, it is also used in the following rule expressions about variables:

$ {Parameter % word }$ {parameter % word}

One % indicates the shortest word match, and two indicates the longest word match.

= Equal sign (Equals)

Symbol that is often seen when a variable is set.

Vara = 123 echo "vara = $ vara"

Or, such as PATH settings, or even applications for such purposes as operations or neural expressions.

= Equal sign (Equals)

It is often seen in the condition criterion, indicating "equal.

If [$ vara = $ varb]

...

! = Not equal

It is often seen in the condition criterion, which indicates the meaning of "not equal.

If [$ vara! = $ Varb]

...

^

In a rule expression, this symbol represents the "beginning" of a row.

We can briefly summarize some common special symbols:

Symbol

Content

#

Annotation Symbol: this symbol is most often used in scripts! The subsequent data does not run

\

Escape Character: Restores a special character or wildcard to a general character.

|

Pipelines: Define commands for separating two pipelines (the last two sections );

;

Delimiter for issuing continuous commands: Definition of continuity commands (note! Different from pipeline commands)

~

User's home directory

$

Use the variable Prefix: that is, the variable to be added before the variable to replace the value

&

Job control: changes a command to work in the background.

!

The meaning of "Non" not in the logic operation sense!

/

Directory symbols: Path-separated symbols

>,>>

Data Stream redirection: output-oriented, namely "Replace" and "accumulate 』

<, <

Data Stream re-orientation: Input orientation (these two are to be discussed in the next section)

''

Single quotes, no variable replacement function

""

Has the function of variable replacement!

''

The two ''are commands that can be run first, or $ ()

()

In the middle is the start and end of the sub-shell

{}

A combination of command blocks in the middle!

3. file descriptor

File Descriptor (File Descriptor), which is represented by a number (usually 0-9. Common file descriptors are as follows:

Default file descriptor name

0 standard input stdin keyboard

1. stdout screen output

2. stderr screen output due to standard errors

Output/input redirection:

>>><<:>&> 2 &> 2 <>>&> & 2

When we simply use <or>, it is equivalent to using 0 <or 1> (we will introduce it in detail below ).

* Cmd> file

Redirects the cmd command output to the file. If the file already exists, the original file is cleared. Use the bash noclobber option to avoid overwriting the original file.

* Cmd> file

Redirects the cmd command output to the file. If the file already exists, add the information to the end of the original file.

* Cmd <file

Read cmd commands from file

* Cmd <text

Read the input from the command line until the end of a line with the same text. Unless input is enclosed by quotation marks, shell variables are replaced in this mode. If <-is used, the tab at the beginning of the input line is ignored. The ending line can also contain a bunch of tabs and add the same content as text. You can refer to the following example.

* Cmd <word

Provide the word (rather than the file word) and the next line feed to cmd as input. * Cmd <> file

The file is redirected to the input in read/write mode, and the file will not be damaged. It makes sense only when the application exploits this feature.

* Cmd> | file

Function>, but the file will be overwritten even when noclobber is set. Note that | is used instead of what is described in some books !, It is still used only in csh>! This function is implemented. :> Filename: truncates the file "filename" to 0. # If the file does not exist, create a 0-length file (same effect as 'touch ).

Cmd> & n sends the output to the file descriptor n

Cmd m> & n redirects the information output to file operator m to file descriptor n cmd> &-Disable Standard output

Cmd <& n input from file descriptor n cmd m <& n m from file description n cmd <&-Disable Standard Input

Cmd <& n-move the input file descriptor n instead of copying it. (Need to explain) cmd> & n-move the output file descriptor n instead of copying it. (Need to be explained)

Note: & actually copied the file descriptor, which makes cmd> file 2> & 1 different from cmd 2> & 1> file.

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.