Special symbols in the shell

Source: Internet
Author: User

The quickest way to learn to write script is to watch someone else's script file. However, although this method is practical, it is often "less effective" or even halfway to the shell's basic cognitive deficit. The first problem is that you don't understand what the "special symbols" mean and what they do.

Below, the farmer tries to list the commonly used special symbol table columns and adds a short example to the description. In principle, "detailed introduction" is not the original intention of this chapter writing. Because of these symbols, the chapters that I intend to write later may reappear. This chapter is therefore only a table column property.
#;;;.,/\' String '
|!$ ${}$?$$$*"String"
***?:^$#[Email protected]' Command '
{}[][[]]()(()) ||&&{Xx,yy,zz,...}
~~+~-&\<...\>+-%
===!=

Output/input re-orientation
>>><<<: >&>2&>2<>
>&>&2

Anyway, for anyone who wants to learn more about the definition of these symbols, the best reference is the online description. and active learning is always one of the best ways. As for the deep understanding and application, it is your own effort.

# pound (comments)

This is almost a full-field symbol, in addition to the "first line" that has been mentioned earlier

#!/bin/bash

The pound sign also often appears at the beginning of a line, or after the complete instruction, which indicates that the symbol is followed by the annotation text and will not be executed.

# This is comments.
echo "a = $a" # a = 0

Because of this feature, when you temporarily do not want to execute a line of instruction, simply add # at the beginning of the line. This is often used in the writing process.

#echo "a = $a" # a = 0

If she is used in an instruction, or surrounded by double quotation marks, or behind a slash, then he becomes a general symbol without the special function described above.

~ Account's Home directory

It's a common symbol, representing the user's home directory.

CD ~

You can also add the name of an account directly after the symbol

CD ~user

Or as part of the path.

~/bin

~+ Current Working Directory

This symbol represents the current working directory, and the role of her and the built-in command pwd is the same.

# echo ~+
/var/log

~-Last working directory

This symbol represents the last working directory.

# echo ~-
/etc/httpd/logs

; Semicolon (Command separator)

In the shell, the symbol that functions as a "continuous instruction" is the semicolon. such as the following example

CD ~/backup; mkdir startup; CP ~/.* startup/.

;; Continuous semicolon (Terminator)

Dedicated in case options, assume the role of Terminator.

Case ' $fop ' in
Help) echo "usage:command-help-version filename";;
Version) echo "version 0.1";;
Esac

. Comma (dot)

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

Cdpath=.:~:/home:/home/web:/var:/usr/local

In the upstream Cdpath setting, the dot after the equals sign represents the meaning of the current directory.

If the file name starts with Dot, the file is a special file, and the LS command must be added with the-a option to display.

In addition, in regular expression, a dot represents a match to a character.

' String ' single quotation mark (quote)

The enclosed quotation marks are treated as a single string. The $ sign that represents the variable within the quotation marks does not function, that is, he is treated as a general symbol.

Heyyou=home
Echo ' $heyyou ' # We get $heyyou

"string" double quotation mark (doubles quote)

The content enclosed in double quotes is treated as a single string. The $ symbol representing the variable within the quotation marks can still be used to substitute variable contents. This is different from the way a single argument is handled.

Heyyou=home
echo "$heyyou" # We get Home

' Command ' inverted quotation marks (backticks)

In the preceding single double quotation mark, enclose the string, but what if the string is a list of command columns? The answer is no execution. To deal with this situation, we have to use a single quotation mark.

fdv= ' Date +%f '
echo "Today $FDV"

The date +%f in the inverted quotation marks is treated as an instruction, and the result of execution is taken into the FDV variable.

, comma (comma)

This symbol is often used in operations as a "partition" use. The following example

#!/bin/bash

let "T1 = ((A = 5 + 3, B = 7-1, c = 15/3))"
echo "T1 = $t 1, a = $a, B = $b"

/slash (forward slash)

When the path is represented, she represents the directory.

Cd/etc/rc.d

Cd.. /..

CD/

Usually single/represents the root root directory meaning. This is quite common and should be easy to understand. In addition, she is also in arithmetic, representing the symbol of division.

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

\ inverted slash (escape)

The escape character in the conversation mode has several functions; before the instruction, there is the function of canceling the aliases, and before the special symbol, the function of the special symbol disappears; At the end of the instruction, the command joins the next line.

# type RM
RM is aliased to ' rm-i '

# \RM./*.log

In the example above, I add the escape character to the RM directive, which is the function of temporarily canceling the alias and restoring the RM instruction.

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

In the above example, the \ $bkdir in echo, Escape will be the function of the $ variable is canceled, therefore, the output $bkdir, and the second $bkdir will output the contents of the variable/home.

| Pipeline (Pipeline)

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

W.H.O. | Wc-l

The use of this concept is very helpful in streamlining script.

! Surprise sighs (negate or reverse)

Usually it represents the function of anti-logic, such as conditional detection, in! = to represent "not equal"

If ["$?"! = 0]
Then
echo "Executes error"
Exit 1
Fi

And, in Regular Expressions, she acted as a "counter-logical" role.

LS A[!0-9]

The above example, on behalf of the exclusion show A0, A1 .... A9 these files.

: Colon

In bash, a colon of two dots is a genuine built-in instruction. She was responsible for doing a great thing, "doing nothing", but responding to a status value of 0.

:
echo $? # response is 0

Take a look at an example of her application.

: > f.$$

The above line, equivalent to Cat/dev/null > f.$$. Not only is the writing brief, but also the implementation of a lot of efficiency.

Sometimes, the following uses of this kind are also present

: ${hostname?} ${user?} ${mail?}

The purpose of this line is to check if these environment variables have been declared and the error messages will be displayed with standard errors. Such a check, if used like test or if, can basically be handled. But it is not comparable to the simplicity and efficiency of the above example.

In addition to the above, there is a place where you must use a colon

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

In the user's own HOME directory, in the. bash_profile or any feature-like file, when setting the "path" variable, we use colons to do the partition. This is one of the occasions she was in bash, another often used.

? Question mark (wild card)

Her role in the filename extension (filename expansion) is to match an arbitrary character, but does not contain a null character.

# ls A?
A1

Make use of her characteristics, you can do more accurate file name matching.

* asterisk (wild card)

A fairly common symbol. On the file name extension (filename expansion), she is used to represent any character, including the null character. I personally like to call him-star brother.

# ls A *
A A1 Access_log

It represents "multiplication" when it is being operated on.

Let "fmult=2*3"

Sorry, the example is a little too much, please forgive my computer, she does not count well. In addition to the built-in instruction let, there is also an instruction expr about the operation, where the asterisk also acts as the "multiplication" role. But be careful in use, he must precede the escape character.

* * Sub-square operation

Two asterisks represent the meaning of the "sub-square" during operation.

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

The farmer has not used it since he knew it, in other words it is called "White Know".

$ money (dollar sign)

Basically, she always means "dollar" to me. If you go to the streets and ask people .... I don't think I'll tell you the following two answers (if any, I'll give you my head).

She is the symbol of variable substitution (Variable Substitution). About this, before this, in fact to durable too many back.

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

In addition, she was defined in Regular Expressions as the end of "line" (End-of-line). This is commonly used in grep, SED, awk, and Vim (vi).

${} variable Parameter Expansion

Bash defines a number of uses for ${}. Here are the table columns taken from the online description

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

This ... is a very small subject. A description of the future option.

$*

It is common to refer to the execution arguments of a script. The algorithm of the argument is the same as the general instruction, the instruction itself is an argument of 0, followed by an argument of 1, and so on. The reference variable is represented in the following way

$ $, $ $, $ $, $ $4, $ $6, $7, $8, $9, ${10}, ${11} .....

Single-digit arguments that use numbers directly, but more than two digits, must be enclosed with the {} symbol.

The $* is the symbol representing all the arguments. When used, you have to add double quotes as appropriate.

echo "$*"

There is also a symbol that has the same effect as the $*, but with a slightly different effect from the way it is handled.

[Email protected]

[Email protected] has the same function as $*, but they have a different point.

The symbol $* treats all the arguments as a whole. However, the symbol [email protected] still retains the concept of the section of each argument. Let's use the For loop to handle the two symbols separately, so we can be clear.

# Cat Arg-02
#!/bin/bash

Index=1

# about $*
Echo-e "\nlisting args with \" \$*\ ":"
For ARG in "$*"
Do
echo "ARG # $index = $arg"
Let "Index+=1"
Done
Echo-e "entire arg list seen as single word.\n\n"

Index=1

# about [email protected]
echo "Listing args with \" \[email protected]\ ":"
For ARG in "[Email protected]"
Do
echo "ARG # $index = $arg"
Let "Index+=1"
Done
echo "Arg list seen as separate words."
#

Here is the result of the execution

#./arg-02 a b c d e F g h i j K

Listing args with "$*":
ARG # = a b c d e F g h i j K
Entire arg list seen as single word.


Listing args with "[email protected]":
Arg #1 = A
Arg #2 = b
Arg #3 = C
Arg #4 = d
Arg #5 = E
Arg #6 = f
Arg #7 = g
Arg #8 = h
Arg #9 = i
Arg #10 = j
Arg #11 = k
ARG list seen as separate words.
#

Be interested to take a look at their differences.

$#

This is also the symbol associated with the argument, and her role is to tell you how much the total number of arguments is.

echo "$#"

$? State value (status variable)

In general, the process of a UNIX (Linux) system is terminated by executing system call exit (). This callback value is the status value. She passes back to parent process as a check for child process execution state usage.

If the execution succeeds, the callback value of the general instruction is 0; the failure is 1. This is used quite frequently when writing script.

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

$$

A simple reference to the execution of the program, which is related to the program. Because the ID of the program is unique, it is not possible to have a repetitive PID at the same time. Understand this point first.

Sometimes writing a script requires a transient file to hold the necessary data. This script may also be used at the same time by the user. In this case, the fixed file name of the transient file, in the wording of the display is not reliable, nor feasible. Only generate a dynamic file name in order to meet the needs. But how to do??

Symbolic $$ may be able to meet this requirement. It represents the PID of the current shell.

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

Use it as part of the file name to avoid overwriting the same file name at the same time.

PS: Basically, the system will recycle the completed PID and then allocate it again as needed. So script even if the temporary archive is the use of dynamic file name, if the script is not cleared after execution, there will be other problems. This point must also be noted.

() instruction Group (command Group)

Enclose a sequence of successive instructions in parentheses, which is called a command group for the shell. As the following example

(CD ~; vcgh= ' pwd '; echo $vcgh)

The command group has a feature that the shell executes in order to generate Subshell to execute this set of instructions. Therefore, the variables defined therein are used only for the instruction group itself. Let's look at an example.

# Cat Ftmp-01
#!/bin/bash
A=fsh
(A=INCG; echo-e "\ n $a \ n")
Echo $a

#./ftmp-01

Incg

Fsh

In addition to the above-mentioned instruction groups, parentheses are used in the definition of the array variable, as well as in other occasions where an escape character may be required to function, such as an expression. I'm not going to give you any examples, and I'll mention them again in subsequent chapters.

(())

The function of this set of symbols is similar to the Let directive and is used in arithmetic operations. It's just that she's Bash's built-in feature. Therefore, it is much better to perform efficiently than to use the Let command.

#!/bin/bash

((a = 10))
Echo-e "inital value, a = $a \ n"

((a++))
echo "After a++, a = $a"

{} curly braces (Block of code)

Sometimes the script appears, and in curly braces there is a paragraph or paragraphs of instructions or variable settings that end with a "semicolon".

# Cat Ftmp-02
#!/bin/bash
A=fsh
{A=INBC; echo-e "\ n $a \ n"}
Echo $a

#./ftmp-02

Inbc

Inbc

This usage is very similar to the instruction group described above, but with a different point, she executes in the current shell and does not produce subshell.

Curly braces are also used in the function of functions. Broadly speaking, simply using curly braces acts like a function that does not have a specified name. Therefore, it is also a good thing to use her to write script. This approach, especially for output input redirection, streamlines the complexity of the script.

In addition, curly braces have another use, as follows

{Xx,yy,zz,...}

This combination of curly braces, commonly used in the combination of strings, look at an example
mkdir {Usera,userb,userc}-{home,bin,data}

We get Usera-home, Usera-bin, Usera-data, Userb-home, Userb-bin, Userb-data, Userc-home, Userc-bin, UserC-data, these few directories. This set of symbols is quite extensive in applicability. If we can make good use of it, the payoff is streamlining and efficiency. Like the following example
Chown Root/usr/{ucb/{ex,edit},lib/{ex?.? *,HOW_EX}}

If it were not for the support of this usage, we have to write a few lines to repeat several times!

[] Brackets

She often appears in the process of control, playing the role of the surrounding judgment. I'm sorry! An example of a cooked
If ["$?"! = 0]
Then
echo "Executes error"
Exit 1
Fi

This symbol acts as a "scope" or "set" role in Regular Expressions.
Rm-r 200[1234]

The above example, represents the deletion of 2001, 2002, 2003, 2004 and so on the meaning of the directory.

In addition, she also has a "double burger" usage

[[]]

This set of symbols is basically the same as the previous [] symbol, but she allows it to be used directly in it | | and && logic and other symbols.
#!/bin/bash
Read AK
if [[$ak > 5 | | $ak < 9]]
Then
Echo $ak
Fi

|| Logical symbols

This will often be seen, representing the or logical symbols.

&& Logic Symbols

This is also often seen, representing and logical symbols.

& Background work

A single & symbol, placed at the end of the complete instruction column, means that the instruction column is placed in the background to work.

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

\<...\> Word boundaries

This set of symbols is defined in Regular Expressions as the meaning of "boundary". For example, when we want to find the word, if we use

grep the FileA

You will find that words such as there are also considered to be matching words. Because the coincidence is part of the there. If we want to avoid this, we have to add the "border" symbol.

grep ' \ ' FileA

That's what she does.

+ PLUS sign (plus)

In an expression, she is used to denote "addition".

Expr 1 + 2 + 3

This should be no problem. In addition she also in Regular Expressions, used to denote "many" the meaning of the front character.

# grep ' 10\+9 ' Fileb
109
1009
100009
1000093
1010009
#

This symbol must be preceded by the escape character when it is used.

-Minus (dash)

In an expression, she is used to denote "subtraction."

Expr 10-2

It is also an option symbol for system directives.

ls-expr 10-2

In the GNU directive, if you use the-symbol alone, without adding any of the file names, she means "standard input". This is a common option for the GNU directive. such as the following example

Tar XPVF-

Here the-symbol, which represents both reading data from the standard input.

However, she is more specific in the CD instructions.

CD-

This represents changing the working directory to the "last" working directory.

% Division (Modulo)

In an expression, she is used to denote "division."

Expr 10% 2

In addition, she is also used in the following Parameter Expansion about variables

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

A% represents the shortest word match, and both represent the longest word match. This project will be described in detail later.

= Equals (equals)

A symbol that is often seen when a variable is set.

Vara=123
echo "Vara = $vara"

Or it is like the setting of PATH, even applied to such uses as arithmetic or judgment.

= = equals (equals)

Often seen in conditional judgments, representing the meaning of "equals".

if [$vara = = $varb]
... Slightly lower

! = does not equal

Often seen in conditional judgments, representing "not equal" meaning.

if [$vara! = $varb]
... Slightly lower

^

This symbol, in regular expression, represents the "start" position of the line.

Output/input re-orientation

The symbols for "output/input redirection" are not only common but also very important foundations.

, >>, <, <<

These four brothers probably don't need to speak more
: &>, 2&>, >&, >&2, 2<>

This hanging brother is actually quite common,Don't dwell on it here.

Special symbols in the shell

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.