手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网站运营>建站经验>列表

Bourne Shell及shell编程(1)

来源:互联网 作者:west263.com 时间:2008-04-16
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

cpio -i $i < /dev/rmt/0h

$restore1 file1

恢复多个文档restoreany :
#restoreany --program to restore a single file
cd $WORKDIR
cpio -i $* < /dev/rmt/0h

$ restoreany file1 file2 file3


(4)条件判断
. if-then语句,格式如下:
if command_1
then
command_2
command_3
fi
command_4

在if-then语句中使用了命令返回码$?,即当command_1执行成功时才执行command_2和
command_3,而command_4总是执行.

示例程式unload: 在备份成功时删除原始文档,带有错误检查

cd
#备份时未考虑不成功的情况!
ls -a | cpio -o > /dev/rmt/0h
rm -rf *

改进如下:

#当使用了管道命令时,管理命令的返回代码为最后一个命令的返回代码
if ls -a | cpio -o > /dev/rmt/0h
then
rm -rf *
fi

. if-then-else语句
if command_1
then
command_2
else
command_3
fi

技巧: 由于shell对命令中的多余的空格不作任何处理,一个好的程式员会用这一特

对自己的程式采用统一的缩进格式,以增强自己程式的可读性.

. 使用test命令进行进行条件测试
格式: test conditions

test在以下四种情况下使用: a. 字符比较 b.两个整数值的比较
c. 文档操作,如文档是否存在及文档的状态等
d. 逻辑操作,能够进行and/or,和其他条件联合使用

a. 测试字符数据: shell变量通常民政部下均作为字符变量
str1 = str2 二者相长,相同
str1 != str2 不同
-n string string不为空(长度不为零)
-z string string为空
string string不为空

例:
$ str1=abcd #在含有空格时必须用引号括起来
$ test $str1=abcd
$ echo $?
0
$ str1="abcd "
$ test $str1=abcd
$ echo $?
1
Note: 在test处理含有空格的变量时最好用引号将变量括起来,否则会出现错误的
结果,
因为shell在处理命令行时将会去掉多余的空格,而用引号括起来则能够防止
shell去掉这些空格.
例:
$ str1=" "
$ test $str1
$ echo $?
1
$ test "$str1"
$ echo $?
0
$ test -n $str1
test: argument expected
$ test -n "$str1"
$ echo $?
0
$

b. 整数测试: test和expr相同,能够将字符型变量转换为整数进行操作,expr进行
整数的算术运算,而test则进行逻辑运算.

表达式 说明
---------------------------------------
int1 -eq int2 相等?
int1 -ne int2 不等?
int1 -gt int2 int1 > int2 ?
int1 -ge int2 int1 >= int2 ?
int1 -lt int2 int1 < int2 ?
int1 -le int2 int1 <= int2 ?

例:
$ int1=1234
$ int2=01234
$ test $int1 -eq $int2
$ echo $?
0

c. 文档测试:检查文档状态如存在及读写权限等

-r filename 用户对文档filename有读权限?
-w filename 用户对文档filename有写权限?
-x filename 用户对文档filename有可执行权限?
-f filename 文档filename为普通文档?
-d filename 文档filename为目录?
-c filename 文档filename为字符设备文档?
-b filename 文档filename为块设备文档?
-s filename 文档filename大小不为零?
-t fnumb 和文档描述符fnumb(默认值为1)相关的设备是个终端设备?

d. 测试条件之否定,使用!
例:
$ cat /dev/null > empty
$ test -r empty
$ echo $?
0
$ test -s empty
1
$ test ! -s empty
$ echo $?
0
e. 测试条件之逻辑运算
-a And
-o Or

例: $ test -r empty -a -s empty
$ echo $?
1
f. 进行test测试的标准方法
因为test命令在 shell编程中占有很重要的地位,为了使shell能同其他编程语言

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!