Shell编程之特殊变量和扩展变量详解

2019-09-23 08:54:31于海丽

状态变量

$?:获取上一个命令或脚本的执行状态值(0:成功,其他:失败) $$:获取当前执行的Shell的进程号(PID) $!:获取上一个在后台工作的进程的进程号 **$_**:获取在些之前执行的命令或脚本的最后一个参数

以上四个状态变量,仅$?常用,其他三个了解即可。

在日常使场景中,$?主要用法如下所示:

1、判断命令和脚本是否执行成功

2、如脚本中调用exit 数字,则会返回该数字给$?

3、如在函数中,则可以通过return 数字将该数字返回给$?

状态变量示例

1、$?示例:

[root@localhost Test]# ll /etc/profile
-rw-r--r--. 1 root root 1819 4月 11 2018 /etc/profile
[root@localhost Test]# echo $?
0
[root@localhost Test]# ll /etc/profild
ls: 无法访问/etc/profild: 没有那个文件或目录
[root@localhost Test]# echo $?
2

2、$$示例:

[root@localhost Test]# cat testPID.sh
#!/bin/bash
echo $$ > /tmp/test.pid
sleep 300

[root@localhost Test]# bash testPID.sh & # 将当前脚本调用到后台执行
[1] 1671
[root@localhost Test]# ps -ef | grep testPID | grep -v grep
root 1671 23706 0 16:37 pts/0 00:00:00 bash testPID.sh # 查询PID

3、!示例:!示例:!功能类似于$$,只不过是获取上一次执行脚本的PID

[root@localhost Test]# bash testPID.sh &
[1] 24078
[root@localhost Test]# echo $!
24078 # 打印上一次在后台执行的进程号
[root@localhost Test]# ps -ef | grep testPID | grep -v grep
root 24078 23706 0 16:42 pts/0 00:00:00 bash testPID.sh

4、$_示例:

[root@localhost Test]# bash para.sh {a..z}
a b c d e f g h i j k l m n o
$0 is: para.sh
$1 is: a
$12 is: l
$# is: 26
$* is: a b c d e f g h i j k l m n o p q r s t u v w x y z
"$*"is: a b c d e f g h i j k l m n o p q r s t u v w x y z
$@ is: a b c d e f g h i j k l m n o p q r s t u v w x y z
"$@"is: a b c d e f g h i j k l m n o p q r s t u v w x y z
[root@localhost Test]# echo $_
z # 打印最后一个传入的参数值

Bash 内置变量

常用的内部命令有echo、eval、exec、export、read、shift、exit。

echo

主要用于打印信息,其命令格式如下所示:

echo [options] args

常用参数如下所示:

参数选项 说明
-n 不换行输出内容
-e 解析转义字符

echo常用转义字符如下:

转义字符 说明
n 换行
r