网普科技
网普管理员
网普科技人民公仆
积分 3080
发贴 2863
注册 2004-6-26 来自 网普科技
状态 离线
|
#1 Linux程式设计-11.Shell Script(bash)--(8)返回状态Exit
在继续下去之前,我们必须要切入另一个话题,即返回状态值 - Exit Status。因为if/while/until都迁涉到了使用Exit Status来控制程式流程的问题。
--------------------------------------------------------------------------------
许多人都知道,在许多语言中(C/C++/Perl....),都有一个exit的函数,甚至连Bash自己都有个exit的内建命令。而exit後面所带的数字,便是返回状态值 - Exit Status。
返回状态值可以使得程式与程式之间,利用Shell script来结合的可能性大增,利用小程式,透过Shell script,来完成很杂的工作。
在shell中,返回值为零表示成功(True),非零值为失败(False)。
--------------------------------------------------------------------------------
举例来说,以下这个两个小程式yes/no分别会返回0/1(成功/失败):
/* yes.c */
void main(void) { exit(0); }
/* no.c */
void main(void) { exit(1); }
那麽以下这个"YES"的shell script便会显示"YES"。
#!/bin/sh
# YES
if yes ; then
echo "YES"
fi
而"NO"不会显示任何东西。
#!/bin/sh
# NO
if no ; then
echo "YES"
fi
--------------------------------------------------------------------------------
test express
[ express ]
在Shell script中,test express/[ express ]这个语法被大量地使用,它是个非常实用的指令。由於它的返回值即Exit Status,经常被运用在if/while/until的场合中。而在後面,我们也会大量运用到,在进入介绍if/while/until之前,有必要先解一下。
其返回值为0(True)或1(False),要看表述(express)的结果为何。
express格式
-b file : 当档案存在并且属性是Block special(通常是/dev/xxx)时,返回True。
-c file : 当档案存在并且属性是character special(通常是/dev/xxx)时,返回True。
-d file : 当档案存在并且属性是目录时,返回True。
-e file : 当档案存在时,返回True。
-f file : 当档案存在并且是正常档案时,返回True。
-g file : 当档案存在并且是set-group-id时,返回True。
-k file : 当档案存在并且有"sticky" bit被设定时,返回True。
-L file : 当档案存在并且是symbolic link时,返回True。
-p file : 当档案存在并且是name pipe时,返回True。
-r file : 当档案存在并且可读取时,返回True。
-s file : 当档案存在并且档案大小大於零时,返回True。
-S file : 当档案存在并且是socket时,返回True。
-t fd : 当fd被开启为terminal时,返回True。
-u file : 当档案存在并且set-user-id bit被设定时,返回True。
-w file : 当档案存在并且可写入时,返回True。
-x file : 当档案存在并且可执行时,返回True。
-O file : 当档案存在并且是被执行的user id所拥有时,返回True。
-G file : 当档案存在并且是被执行的group id所拥有时,返回True。
file1 -nt file2 : 当file1比file2新时(根据修改时间),返回True。
file1 -ot file2 : 当file1比file2旧时(根据修改时间),返回True。
file1 -ef file2 : 当file1与file2有相同的device及inode number时,返回True。
-z string : 当string的长度为零时,返回True。
-n string : 当string的长度不为零时,返回True。
string1 = string2 : string1与string2相等时,返回True。
string1 != string2 : string1与string2不相等时,返回True。
! express : express为False时,返回True。
expr1 -a expr2 : expr1及expr2为True。
expr1 -o expr2 : expr1或expr2其中之一为True。
arg1 OP arg2 : OP是-eq[equal]、-ne[not-equal]、-lt[less-than]、-le[less-than-or-equal]、-gt [greater-than]、-ge[greater-than-or-equal]的其中之一。
--------------------------------------------------------------------------------
在Bash 中,当错误发生在致命信号时,bash会返回128+signal number做为返回值。如果找不到命令,将会返回127。如果命令找到了,但该命令是不可执行的,将返回126。除此以外,Bash本身会返回最後一个指令的返回值。若是执行中发生错误,将会返回一个非零的值。
Fatal Signal : 128 + signo
Can't not find command : 127
Can't not execute : 126
Shell script successfully executed : return the last command exit status
Fatal during execution : return non-zero
原作者: 不详
来 源: 不详
|
天理路上甚宽,稍游心,胸中便觉广大宏朗;
人欲路上甚窄,才寄迹,眼前俱是荆棘泥涂。
网普科技,优质美国主机服务!
美国Linux主机,美国虚拟主机
支持PHP+MYSQL+cPanel+EMAIL
为用户负责,拒绝反动、赌博及色情内容! QQ:126818
发送QQ消息 |
|