PHP和shell脚本遍历目录及其下子目录

时间:2023-03-08 23:34:57
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 . ':\r\n';
traverse($sub_dir);
} else { //如果是文件,直接输出
echo 'File in Directory ' . $path . ': ' . $file . '\r\n';
}
}
}
/*$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 这样任何目录下都可访问了。】