zoukankan      html  css  js  c++  java
  • PHP和shell脚本遍历目录及其下子目录

    shell写了个递归遍历目录的脚本,本脚本实现递归遍历指定目录,打印目录下的文件名(全路径)。

     #!/bin/sh   
        
    function scandir() {   
        local cur_dir parent_dir workdir   
        workdir=$1   
        cd ${workdir}  
     
        if [ ${workdir} = "/" ]   
        then   
            cur_dir=""   
        else   
            cur_dir=$(pwd)   
        fi   
      
       for dirlist in $(ls ${cur_dir})   
       do   
               if test -d ${dirlist}
            then   
               cd ${dirlist}   
               scandir ${cur_dir}/${dirlist}   
               cd ..   
           else   
              echo ${cur_dir}/${dirlist} 
           fi   
       done   
    }   
      
    if test -d $1   
    then   
       scandir $1   
    elif test -f $1   
        then   
            echo "you input a file but not a directory,pls reinput and try again"   
               exit 1   
        else   
               echo "the Directory isn't exist which you input,pls input a new one!!"   
               exit 1   
    fi  

    =================下面用php命令行执行php脚本============================

    <?php
                function traverse($path = '.') {
                    $current_dir = opendir($path);    //opendir()返回一个目录句柄,失败返回false
                    while(($file = readdir($current_dir)) !== false) {    //readdir()返回打开目录句柄中的一个条目
                        $sub_dir = $path . DIRECTORY_SEPARATOR . $file;    //构建子目录路径
                        if($file == '.' || $file == '..') {
                            continue;
                        } else if(is_dir($sub_dir)) {    //如果是目录,进行递归
                            echo 'Directory ' . $file . ':
    ';
                            traverse($sub_dir);
                        } else {    //如果是文件,直接输出
                            echo 'File in Directory ' . $path . ': ' . $file . '
    ';
                        }
                    }
                }
               /*$argc 表示传入php参数个数,$agrv表示传入的参数数组
                *类似于 array('xxxx.php','参数1','参数2');
                */
                if($argc==2){
                  $path=$argv[1];
                } else{
                   die('error msg!');
                }
                if(!is_dir($path)){
                  exit($path.' is not a directry!');
                }
                traverse($path);
    
            ?>

    终端这样调用:[root@xiuran test]# php scan.php /mybak/

    这样就和上边的执行结果一样。【前提php命令要在当前目录下能够执行,可以做一个软连接: ln -s /usr/local/php/bin/php  /sbin/php 这样任何目录下都可访问了。】
  • 相关阅读:
    sizeof()和 strlen()的区别 --- 个人笔记
    MySQL 生成自增流水号
    sql 逗号分隔列转行
    【转】.NET中lock的使用方法及注意事项
    【转】在一个SQL Server表中一行的多个列找出最大值
    使用 PIVOT 和 UNPIVOT
    List<T>转DataTable
    C# 分数计算类(加减乘除)
    【转】mysql执行计划介绍
    【转】SQL Server 存储:理解IAM 页
  • 原文地址:https://www.cnblogs.com/lixiuran/p/3699938.html
Copyright © 2011-2022 走看看