Summary of special symbols in the shell

Source: Internet
Author: User
Tags arithmetic

The special symbols commonly used in the shell are listed below:

# ; ;; .   ,/\ \ ' String ' |! $   ${}   $? $$   $*

\ "string\" * * *? : ^ $# [email protected] ' command ' {} [] [[]] () (())

|| && {Xx,yy,zz,...} ~ ~+ ~-& \\<...\\> +-%= = = =


# pound (comments)
This is almost a full-field symbol, in addition to the previous mentioned \ "First line \"
#!/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 it is used in an instruction, or enclosed in double quotation marks, or behind a slash, then he becomes a general symbol, without the specialFunction.


~ account's home directory
is 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
~+ the 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 \ "Continuous instruction \" is \ "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 \" inhelp) echo \ "Usage:command-help-version filename\";; Version) echo \ "version 0.1\";; Esac


. Comma (dot, which is "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 RegularExpression, 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 work, that is, he is treated as a general symbol and prevents any variable substitution.
Heyyou=homeecho ' $heyyou ' # We get $heyyou


\ "string\" double quotation marks (doubles quote)
The content enclosed in double quotes is treated as a single string. It prevents wildcard expansion, but allows variable expansion. This is different from the way a single argument is handled.
Heyyou=homeecho \ "$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 (commas in comma, punctuation)
This symbol is often used in operations as a "partition \" use. The following example
#!/bin/bashlet \ "T1 = ((A = 5 + 3, B = 7-1, c = 15/3)) \" echo \ "t1= $t 1, a = $a, B = $b \"


/Slash (forward slash)
Represents the directory when the path is represented.
CD/ETC/RC.DCD. /.. CD/
Usually single/represents the root root directory meaning; in arithmetic, a symbol representing division.
Let \ "NUM1 = ((a = 10/2, B = 25/5)) \"


\ Inverted Slash
The escape character in interactive 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; placed at the very end of the instruction, indicating that the command joins the next line.
# type RMRM 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.


| pipe (Pipeline)
Pipeline is UNIX.Systems, fundamental and important concepts. 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.


! exclamation point (negate or reverse)
Usually it represents the function of anti-logic, such as conditional detection, using! = to represent \ "Not equal to \"
if [\ "$?\"! = 0]thenecho \ "Executes error\" Exit 1fi
In the rule expression she acts as the \ "anti-logic \" role
LS A[!0-9]
In the example above, the representative shows that except A0, A1 .... A9 these fewOther files of the file.


: Colon
In bash, this is a built-in directive: \ "Nothing is done", but returns the status value 0.
:
echo $? # response is 0
: > f.$$
The above line, the equivalent of 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 beenSettings, the error message will be displayed with a standard error if not set. Such checks, like test or if, can basically be dealt with, but not as simple and efficient as the example above.


? Question mark (wild card)
The role played on 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.
# ls a*a A1 Access_log
At the time of operation, it represents \ "multiplication \".
Let \ "Fmult=2*3\"
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 \ "secondary \" when operating.
Let \ "sus=2**3\" echo \ "sus = $sus \" # SUS = 8


$ money (dollar sign)
variable Substitution(Variable Substitution) is a representative symbol.
Vrs=123echo \ "VRS = $vrs \" # VRS = 123
In addition, the Regular Expressions is defined as the end of \ "line \" (End-of-line). This is commonly used in grep, SED, awk, and Vim (vi).


Regular expressions for ${} variables
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} ${parameterffset} ${parameterffset:l Ength} ${!prefix*} ${#parameter} ${parameter#word} ${parameter# #word} ${parameter%word} ${parameter%%word} $ {parameter/pattern/string} ${parameter//pattern/string}


$*
$* Referencing a script's execution reference variable, the algorithm referencing the parameter is the same as the general instruction, the instruction itself is 0, followed by 1, and so on. The reference variable is represented in the following way:
$ $, $ $, $ $, $ $4, $ $6, $7, $8, $9, ${10}, ${11} .....
Single digit, you can use the number directly, but more than two digits, you must use the {} symbol to enclose.
$* is the symbol that represents all reference variables. 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 reference variables as a whole. However, the symbol [email protected] still retains the concept of the section of each reference variable.

$#
This is also the symbol associated with the reference variable, and her role is to tell you what the total number of reference variables is.
echo \ "$#\"


$? Status value(Status variable)
Generally, the process of a UNIX (Linux) system ends with the execution of the system call exit (). This callback value is the status value. Passed back to the parent process to check the execution status of the child process.
General InstructionsIf the program succeeds, the callback value is 0 and the failure is 1.
Tar cvfz dfbackup.tar.gz/home/user >/dev/nullecho\ "$?\" $$
Because the ID of the process is unique, it is not possible to have a repetitive PID at the same time. Sometimes, script will need to generate temporary files to hold the necessary information. This script may also be used by users at the same time. In this case, the fixed file name is not reliable in the notation. Only a dynamic file name can be generated to meet the needs. 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 file is written using a dynamic file name, there are other problems if the script is not cleared after execution.

() 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 instruction group has an attribute, and the shell executes the set of instructions in order to generate Subshell. Therefore, the variables defined therein are used only for the instruction group itself. Let's look at an example.
# cat Ftmp-01#!/bin/basha=fsh (A=INCG; echo-e \ "\\n $a \\n\") echo $a #./ftmp-01incgfsh
In addition to the above-mentioned instruction group, parentheses are used in the definition of the array variable, as well as in other occasions where the escape character may need to be used, such as an expression.


(( ))
This set of symbols is similar to the Let directive, and is used in arithmetic operations, which is the built-in function of bash. Therefore, it is much better to perform efficiently than to use the Let command.
#!/bin/bash ((a = ten)) 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 with a "semicolon \" that ends the instruction or variable setting.
# cat FTMP-02#!/BIN/BASHA=FSH{A=INBC, ECHO-E \ "\\n $a \\n\"}echo $a #./ftmp-02inbcinbc
This usage is very similar to the instruction group described above, but with a different point, it executes in the current shell and does not produce subshell.
Curly braces are also used in the function \ function. Broadly speaking, simply using curly braces acts like a function that does not have a specified name. So writing script like this is a pretty good thing. 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
Often appear in the process control, play the role of the surrounding judgment. if [\ "$?\"! = 0]thenecho \ "Executes error\" Exit1fi
This symbol acts like \ "Scope \" or \ "collection \" in regular expressions
Rm-r 200[1234]
The above example, representingDelete the 2001, 2002, 2003, 2004, and so on directory meaning.


[[ ]]
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/bashread Akif [[$ak > 5 | | $ak < 9]]thenecho $AKFI


| | 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 put into the background to work.
Tar cvfz data.tar.gz data >/dev/null&

\\<...\\> Word Boundaries
This set of symbols is defined in the rule expression 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 situation, we have to add the "boundary \" symbol
grep ' \ \ ' FileA


+ plus sign (plus)
In an expression, she is used to denote \ "addition \".
Expr 1 + 2 + 3
In addition, in the rule expression, the meaning of the preceding character of \ "many \" is used.
# grep ' 10\\+9 ' fileb109100910000910000931010009# This symbol must be preceded by escape characters when 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 the-symbol is used alone, it means "standard input \" without adding any of the added file names. 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, in the CD instructions are more special
CD-
This represents changing the working directory to \ "last \" working directory.


% Division (Modulo)
In an expression, it is used to denote \ "division \".
Expr 10% 2
In addition, the following are used in the regular expressions about variables
${parameter%word}${parameter%%word}
A% represents the shortest word match, and both represent the longest word match.


= equals (equals)
A symbol that is often seen when a variable is set.
Vara=123echo \ "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 see in the conditional judgment, representing \ "Not equal to \" meaning.
if [$vara! = $varb]
... Slightly lower


^
This symbol, in the regular expression, represents the \ "start \" position of the row, and in [] is also the same as \ "!\" (exclamation mark), which means "non"


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

File descriptor, which represents a file with a number (usually 0-9).
The usual file descriptors are as follows:
file Descriptor name common abbreviation default value
0 Standard Input stdin keyboard
1 Standard output stdout screen
2 standard error Output stderr screen
We use 0< or 1> when we simply use < or > (described in more detail below).
* cmd > file
Redirects the output of the cmd command to the file. If file already exists, empty the original, and use Bash's noclobber option to prevent the old file from being covered.
* cmd >> file
Redirect the output of the cmd command to the file, and if file already exists, add the information to the back of the original file.
* cmd < file
To enable the CMD command to read from file
* cmd << text
Reads the input from the command line until a line with the same text ends. Unless you enclose the input in quotation marks, this mode will replace the shell variable with the input. If you use <<-, you will ignore the tab at the beginning of the line, the end row can also be a bunch of tabs plus a text with the same content, you can refer to the following example.
* cmd <<< word
Provide CMD with Word (instead of file word) and a newline as input.
* cmd <> file
The file is redirected to input in read-write mode, and file files are not corrupted. It makes sense only when the application takes advantage of this feature.
* cmd >| file
function of the same, but even when the noclobber is set to cover file file, note that the use of | and not some of the book said!, currently only in the CSH >! to achieve this function.
: > FileNameTruncate the file \ "filename\" to 0 length. # If the file does not exist, create a 0-length file (the same effect as ' touch ').
cmd >&nSend output to file descriptor N
cmd m>&nRedirect information from output to file m to file descriptor N
cmd >&-Turn off standard output
cmd <&nInput from File descriptor n
cmd m<&nm from the file describing each n
cmd <&-Turn off standard input
cmd <&n-Move the input file descriptor n rather than copy it. (need to explain)
cmd >&n-Move the output file descriptor n rather than copy it. (need to explain)
Note: >& actually duplicates the file descriptor, which makes the cmd > file 2>&1 different from the cmd 2>&1 >file.  

Http://hi.baidu.com/hellosimple/blog/item/559483f1f1c0e95e352acc89.html

http://blog.csdn.net/mqboss/article/details/6549176

1. {} curly braces:
Usage One: Wildcard extension

Code:
ls my_{finger,toe}s


This command is equivalent to a combination of the following commands:

Code:
ls my_fingers my_toes
mkdir {userA,userB,userC}-{home,bin,data}


We will get Usera-home, Usera-bin, Usera-data, Userb-home, Userb-bin,userb-data,userc-home, Userc-bin, UserC-data, these several directories
Usage Two: Can be used for the construction of statement blocks, between statements separated by carriage return. If you want to use multiple statements in certain places where a single statement is used, such as in an and or or list, you can construct a block of statements by enclosing them in curly braces {}.

Code:
grep -v "$cdcatnum" $strack_file > $temp_file
cat $temp_file > $strack_file
echo
cat -n file1


(Note: The four sentences in the curly braces above are enough to be a block of statements)
Usage three: Parameter extension

Code:
${name:-default} 使用一个默认值(一般是空值)来代替那些空的或者没有赋值的变量name;
${name:=default}使用指定值来代替空的或者没有赋值的变量name;
${name:?message}如果变量为空或者未赋值,那么就会显示出错误信息并中止脚本的执行同时返回退出码1。
${#name} 给出name的长度
${name%word} 从name的尾部开始删除与word匹配的最小部分,然后返回剩余部分
${name%%word} 从name的尾部开始删除与word匹配的最长部分,然后返回剩余部分
${name#word} 从name的头部开始删除与word匹配的最小部分,然后返回剩余部分
${name##word} 从name的头部开始删除与word匹配的最长部分,然后返回剩余部分


(Note, name is the variable name, Word is the string to match)
Usage three is useful when dealing with strings and unknown variables.

2, [] brackets:
Usage One: Wildcard extension:
Allow matching of any single character in square brackets

Code:
ls /[eh][to][cm]*


Equivalent to executing ls/etc/home (if there is a/eom directory, it is equivalent to executing ls/etc/home/eom)
Note: cannot be extended under the mkdir command
Usage two: Used for conditional judgment symbols:
The [] symbol can be interpreted as a soft link to the test command, so its usage can be fully referenced by test, and the test location will be replaced with [.

Code:
if [ "$?" != 0 ] 等价于 if test "$?" != 0
then echo "Executes error"



3. ' Command ' anti-quote:
' Command ' has the same meaning as $ (command), which returns the result of the current execution command.

Code:
#!/bin/sh
for file in $(ls f*.sh);do
    lpr $file
done
exit 0


This example implements the name of the file that extended f*.sh gives all matching patterns.

4, ' string ' single quote and ' string ' double quotation marks
Double quotation marks: If you want to add a space to a defined variable, you must use single or double quotation marks.
The difference between single and double quotes is that double quotes escape special characters and single quotes do not escape special characters

Code:
$ heyyou=home
$ echo ‘$heyyou‘
$ $heyyou ($没有转义)
eg: $ heyyou=home
$ echo "$heyyou"
$ home (很明显,$转义了输出了heyyou变量的值)



5, $# its role is to tell you the total number of reference variables is how much;

Code:
$$ 它的作用是告诉你shell脚本的进程号;
$* 以一个单字符串显示所有的脚本传递的参数。等价于$1 $2 $3.......;
[email protected] 与$*基本类似(参见序号7),但在数组赋值时有些不同;
$? 前一个命令的退出码;
$- 显示shell使用的当前选项;
$! 最后一个后台运行的进程ID号。



6, $ ((...)) Syntax: Evaluating an expression within parentheses

Code:
#!/bin/sh
x=0
hile [ "$x" -ne 10 ];do
echo $x
x=$(($x+1))
done
exit 0



7. References to several special parameter variables in the shell

Code:
$1、$2、$3……${10}、${11}、${12}…… :表示脚本传入的的各个参数,注意当需表示两位数以后的参数时数字要用花括号括起。
[email protected] 列出所有的参数,各参数用空格隔开
$*: 列出所有的参数,各参数用环境变量IFS的第一个字符隔开



8. List of commands:
and list statement1 && statement2 && statement3 && ...: Executes the latter command only if all previous commands are executed successfully
or List statement1 | | Statement2 | | Statement3 | | ...: Allows a series of commands to be executed until one command succeeds, and all subsequent commands are no longer executed
#!/bin/sh

Code:
touch file_one
rm -f file_two
if [ -f file_one ] && echo "hello" && [ -f file_two ] && echo " there"
then
echo "in if"
else
echo "in else"
fi
exit 0


The output of the above example is:

Code:
hello
in else


The list of and lists and or lists are used in logical judgments, and the following is the most common example:

Code:
[ condition ] && command for true || command for false:


Executes commandfor true when the condition is true, and executes command for false when the condition is false

9,: Colon: Built-in null instruction, return value is 0

Code:
$ :
$ echo $?
$ 0
while: (该语句结构可实现一个无限循环)



10,; Semicolon: In the shell, the symbol that functions as a "continuous instruction" is a semicolon.

Code:
cd ~/backup ; mkdir startup ; cp ~/.* startup/.



11, #: Indicates that the symbol is followed by the annotation text, will not be executed;

Code:
* 匹配文件名中的任何字符,包括字符串;
? 匹配文件名中的任何单个字符。
~ 代表使用者的 home 目录



12,/Inverted slash:
The function of canceling the aliases (alias) before the instruction is placed;
Before the special symbol is placed, the function of the special symbol disappears;
At the very end of the instruction, indicating that the command joins the next line (which makes the carriage return invalid and only acts as a newline)

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

14, * * Sub-square operation: Two asterisks represent the meaning of "the second party" in operation

Code:
let "sus=2**3"
echo "sus = $sus"
$ sus = 8 -

Summary of 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.