In the Shell $
is a special character, have different uses in different scenarios.
Reference variable
Use $
direct reference variables, including loop variable.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# x=1 |
Double quotes "
string enclosed support variable interpolation.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# x=1 |
Use ${}
as a word boundary.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:/var/log/nginx# x=1 |
Use $ {#} acquisition variable length string.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:/var/log/nginx# s=hello |
The script that references or function parameters
Based on the subject under reference, 0 represents the shell script file name, n represents the n argument starting at 1, the first argument is $ 1.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# echo 'echo $0 $1' > test.sh |
Note that single quote '
string enclosed not interpolated.
Use $#
to get the script or number of arguments.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# echo 'echo $#' > test.sh |
Use $@
or $*
reference list of arguments as an array. The difference is that with the use of double quotation marks, it is assumed the incoming parameters 1 2 3
, then the "$@"
value of "1", "2", "3" three variables, $*
a value of "1 2 3" is a variable.
test.sh
1 |
echo using '$@' |
1 |
root @ iZ2ze43t8c5urajez large column Linux Shell the N kinds of usage '$' symbol 7ws4eZ: ~ # 2. 3. 1 SH test.sh |
The return value of the last command
Use $?
the return value of a command. 0 indicates a successful execution, non-zero value indicates an error, note differs from the C language here.
$?
The easy to remember name, query presents to ask OS, how about the result of last executed command it? Note that each execute a command will override this variable.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# true |
Execute commands and get output
Use $()
executed and acquires command output assigned to variables, functions equivalent to double quotes.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# echo `date` |
Expression evaluation
Use $[]
of the expression is evaluated, and the expr
command is different, $[]
for the interpolation, and expr
the value is output.
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# $[ 1 + 1 ] |
获取当前进程ID
使用$$
获取当前进程ID。
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# echo $$ |
后台运行的最后一个进程ID
使用$!
获取后台运行的最后一个进程ID,在命令后面使用&
即可以创建后台进程。
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# tail -f /var/log/nginx/access.log & |
获取shell选项
使用$-
获取当前shell的选项。具体的选项意义可以参考segmentfault上的回答。
1 |
root@iZ2ze43t8c5urajez7ws4eZ:~# echo $- |