跟我一起学<perl系统管理脚本> 第2课

简介:
今天是perl系统管理脚本的第二课,内容和第一课差不多,不过第二课是对第一课有了进一步深入的使用,如将功能集成化,还有实现了递归调用........大家可以模仿这个做类似的脚本.......
#*
#* scans a filesystem "by hand" for core files with optional deletion
#*
#!/usr/bin/perl -s
# note the use of -s for switch processing. Under NT/2000, you will need
# call this script explicitly with -s (i.e. perl -s script) if you do not
# have perl file associations in place.
#
# -s is also considered 'retro', many programmers preferring to load
# a separate module (from the Getopt:: family) for switch parsing.
use Cwd; # module for finding the current working directory
# This subroutine takes the name of a directory and recursively scans
# down the filesystem from that point looking for files named "core"
sub ScanDirectory{   #目录扫描函数
    my ($workdir) = shift;  #保存函数传递的参数
    my ($startdir) = &cwd; # keep track of where we began #记录当前工作目录
    chdir($workdir) or die "Unable to enter dir $workdir:$!\n"; #转到扫描目录下
    opendir(DIR, ".") or die "Unable to open $workdir:$!\n";    #打开目录句柄
    my @names = readdir(DIR) or die "Unable to read $workdir:$!\n"; #将目录下的内容赋值给数组
    closedir(DIR);
    foreach my $name (@names){
        next if ($name eq ".");
        next if ($name eq "..");
        if (-d $name){ # is this a directory?
            &ScanDirectory($name);  #再次调用这个函数
            next;
        }
        if ($name eq "core") { # is this a file named "core"?
            # if -r specified on command line, actually delete the file
            if (defined $r){
                unlink($name) or die "Unable to delete $name:$!\n";
            }
            else {
                print "found one in $workdir\n";
            }
        }
    }
    chdir($startdir) or die "Unable to change to dir $startdir:$!\n";
}
&ScanDirectory(".");
[学习]
     这课有个特色就是循环的读取某个指定目录,直到在指定的目录下没有目录了.一次又一次的将与指定的文
件进行匹配.在这里,我们看到了,将某一个功能集成化,就是把目录扫描文件的功能写到一个函数了,在借助CWD模
块,记录当前工作目录,以实现递归的查找文件,当符合条件时,采取一定的动作,如删除.......


本文转自hahazhu0634 51CTO博客,原文链接:http://blog.51cto.com/5ydycm/115388,如需转载请自行联系原作者
相关文章
|
2月前
|
监控 Shell
Shell脚本实战教学
Shell脚本实战教学
26 5
|
7月前
|
弹性计算 缓存 监控
Linux指令入门-系统管理
本场景将介绍Linux中常用的系统工作命令以及系统状态检测命令
250 0
|
4月前
|
Shell 应用服务中间件 Linux
小白带你学习linux的shell脚本基础(三十五)
小白带你学习linux的shell脚本基础(三十五)
64 0
|
运维 Shell Linux
《Shell 脚本速查手册》电子版
编写Bash脚本耗时长?不稳定?有妙招!阿里云开发者社区和linux中国开源社区联手推出《Shell脚本速查手册》,为运维工程师提供一个快速、便捷的查询手册,以共开发者查询自己日常工作中常用的命令和脚本。
144 0
《Shell 脚本速查手册》电子版
|
Shell Linux
Linux复习资料——一篇文章学会sh脚本的编写(3)
Linux复习资料——一篇文章学会sh脚本的编写
67 0
Linux复习资料——一篇文章学会sh脚本的编写(3)
|
Shell Linux 开发工具
Linux复习资料——一篇文章学会sh脚本的编写(2)
Linux复习资料——一篇文章学会sh脚本的编写
101 0
Linux复习资料——一篇文章学会sh脚本的编写(2)
|
Shell Linux
Linux复习资料——一篇文章学会sh脚本的编写(1)
Linux复习资料——一篇文章学会sh脚本的编写
147 0
Linux复习资料——一篇文章学会sh脚本的编写(1)
|
移动开发 Shell Linux
《Linux Shell脚本攻略》 笔记 第四章:高效文本处理
《Linux Shell脚本攻略》 笔记 第四章:高效文本处理
169 0
|
Shell Linux Perl
《Linux Shell脚本攻略》 笔记 第九章:进程管理
《Linux Shell脚本攻略》 笔记 第九章:进程管理
143 0
|
Linux Shell 网络安全
《Linux Shell脚本攻略》 笔记 第八章:磁盘、日志管理
《Linux Shell脚本攻略》 笔记 第八章:磁盘、日志管理
89 0