linuxshell编程指南第十九章------shell函数1

浏览:
字体:
发布时间:2013-12-15 22:18:43
来源:

在菜单中进行选择时,最麻烦的工作是必须在选择后键入回车键,或显示“ press any key to continue”。可以使用dd命令解决不键入回车符以发送击键序列的问题。

dd命令常用于对磁带或一般的磁带解压任务中出现的数据问题提出质疑或转换,但也可用于创建定长文件。下面创建长度为1兆的文件my file。
[root@localhost huangcd]# dd if=/dev/zero of=myfile11 count=512 bs=2048
512+0 records in
512+0 records out
1048576 bytes (1.0 MB) copied, 0.0106073 seconds, 98.9 MB/s
[root@localhost huangcd]# ls -al |grep "myfile11"
-rw-r--r-- 1 root root 1048576 12-11 12:32 myfile11

拷贝文件时,测试目录是否存在是常见的工作之一。以下函数测试传递给函数的文件名是否是一个目录。因为此函数返回时带有成功或失败取值,可用i f语句测试结果。
[root@localhost huangcd]# cat is_it_directory
#!/bin/bash
is_it_directory(){
if [ $#-lt1 ]
then
echo "is_it_directory:I need an angument"
return 1
fi
_DIRECTORY_NAME=$1
if [ !-d $_DIRECTORY_NAME ]
then
return 1
else
return 0
fi
}
echo -n "enter destination directory:"
read DIREC
if is_it_directory $DIREC
then
echo "$DIREC does not exist,create it now?[y..n]"
fi

if语句总结:

总结:

1.if后要有空格

2.[] 中括号的开头和结尾要有空格!

3. [ $1-eq"root" ]中括号中的$1和-eq和"root"之间没有空格!

在v i编辑器中,可以列出行号来进行调试,但是如果打印几个带有行号的文件,必须使用nl命令。以下函数用n l命令列出文件行号。原始文件中并不带有行号。

要调用n u m b e r f i l e函数,可用一个文件名做参数,或在s h e l l中提供一文件名,例如:
$ number_file myfile

也可以在脚本中这样写或用:
number_file $1

number_file()
{
_FILENAME=$1
if [ $# -ne 1 ]
then
echo "number_file:I need a filename to number"
return 1
fi
loop=1
while read LINE
do
echo "$loop:$LINE"
loop=`expr $loop + 1`
done<$_FILENAME
}
[root@localhost huangcd]# number_file /home/huangcd/ok.txt
1:AC456
2:AC492169
3:AC9967
4:AC88345

使用函数的两种不同方法:从原文件中调用函数和使用脚本中的函数。

使用脚本中的函数的话,只要保证函数在调用之前已经定义好。

现在编写脚本就可以调用f u n c t i o n s . s h中的函数了。注意函数文件在脚本中以下述命令格式定位:
./<path to file>

使用这种方法不会创建另一个s h e l l,所有函数均在当前s h e l l下执行。

[root@localhost huangcd]# cat functions.sh
#!/bin/bash
func1()
{
echo "func1() is used"
}
[root@localhost huangcd]# cat direc_check
#!/bin/bash
. /home/huangcd/functions.sh
func1
echo "func1 is used in direc_check"
[root@localhost huangcd]# sh direc_check
func1() is used
func1 is used in direc_check

>更多相关文章
24小时热门资讯
24小时回复排行
资讯 | QQ | 安全 | 编程 | 数据库 | 系统 | 网络 | 考试 | 站长 | 关于东联 | 安全雇佣 | 搞笑视频大全 | 微信学院 | 视频课程 |
关于我们 | 联系我们 | 广告服务 | 免责申明 | 作品发布 | 网站地图 | 官方微博 | 技术培训
Copyright © 2007 - 2024 Vm888.Com. All Rights Reserved
粤公网安备 44060402001498号 粤ICP备19097316号 请遵循相关法律法规
');})();