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

来源:互联网 发布:ip地址和域名的关系 编辑:程序博客网 时间:2024/05/17 03:00
在菜单中进行选择时,最麻烦的工作是必须在选择后键入回车键,或显示“ press any key
to continue”。可以使用d d命令解决不键入回车符以发送击键序列的问题。
d d命令常用于对磁带或一般的磁带解压任务中出现的数据问题提出质疑或转换,但也可

用于创建定长文件。下面创建长度为1兆的文件m y f i l e。

[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编辑器中,可以列出行号来进行调试,但是如果打印几个带有行号的文件,必须使用
n l命令。以下函数用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

2 0
原创粉丝点击