xDroid's Blog

20.2 Shell 的特殊变量 (从新手到菜鸟的Linux教程)

上次说了怎么自定义变量,这次看一下一些特殊的变量。

感觉最常用的肯定就是传入参数 $[n] 嘛!其他什么基本用不到的。

比如说如果脚本是这样调用的

$ SCRIPT_NAME PARAMETER_1 PARAMETER_2 [...] PARAMETER_N

那么变量 $0 就是 SCRIPT_NAME , $1 就是 PARAMETER_1 ,以此类推……挺好记的是吧。

$# 是参数的数量,但本人觉得用处不大,因为有 shift

其他一些奇葩的就一笔略过,大家自己去看 manual 好了;这里可以提一下 $? ,这个变量是指上一个前台脚本的返回值,比如

$ false
$ echo $?
1
$ true
$ echo $?
0

当然不只有 0 和 1 这两个值……哦顺便提一句, shell 习惯上是 0 表示成功,非 0 值表示异常,这个后面也会用到的。


提示符系列,你们看看就好。

变量名 用途
PS0 The value of this parameter is expanded (see PROMPTING below) and displayed by interactive shells after reading a command and before the command is executed.
PS1 The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string. The default value is \s-\v\$ .
PS2 The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is > .
PS3 The value of this parameter is used as the prompt for the select command (see SHELL GRAMMAR above).
PS4 The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is + .

于是通过这个变量加上 PS1 这个特殊变量就可以造出提示上一次命令是否成功的 prompt

PS1="${debian_chroot:+($debian_chroot)}\[\033[01;34m\]\u\[\033[00m\][\[\033[01;34m\]\w\[\033[00m\]]\`[ \$? -eq 0 ] && echo || echo \[\e[01\;41m\]!\[\e[0m\]\`\$ "

然鹅现在我在用 oh-my-zsh