首页 > 系统 > Linux > 正文

shell脚本递归遍历目录及子目录的例子分享

2019-10-26 18:40:25
字体:
来源:转载
供稿:网友

用shell写的递归遍历目录的脚本,脚本实现递归遍历指定目录,打印目录下的文件名。

实例1:
代码如下:
#!/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

实例2:递归读取目录及其子目录
代码如下:#! /bin/bash
function read_dir(){
    for file in `ls $1`
    do
        if [ -d $1"/"$file ]  //注意此处之间一定要加上空格,否则会报错
        then
            read_dir $1"/"$file
        else
            echo $1"/"$file
        fi
    done
}

#测试目录 test
read_dir test
这样给test.sh加上执行权限即可执行
代码如下:chmod +x test.sh
sh test.sh
到此即可通过传递参数来读取目录文件了。

实例3:

代码如下:
递归实现各个子目录孙目录......

#!/bin/bash

#modify.func

doit()   //处理当前目录下的非目录文件,忽略目录文件

{

    oldname=`ls | grep "$1$"`

    for name in $oldname

    do

       if [ -d "$name" ]

       then :

       else

            basename=`echo $name | awk -F "." '{print $1}'`  

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表