Bash Shell遍历目录

本文介绍了一种使用Bash脚本语言实现的目录遍历方法,包括深度优先搜索(DFS)和广度优先搜索(BFS)。通过递归地访问文件系统中的每个目录和文件,展示了如何利用Bash内置命令完成这两种经典的图遍历算法。

点击打开链接



#!/bin/bash
 
# http://ouonline.net/
 
IFS=$(echo -en "\n\b") # in case of space(s) in dentry name
 
# -------------------------------------------------------------------------- #
 
function dfs()
{
    #if [ $# -ne 2 ]; then
        #echo "function call error: dfs callback root_dir" >&2
        #exit -1
    #fi
 
    callback=$1
    root=$2
 
    let top=1
    stack[0]="$root" # root dir
 
    while [ $top -gt 0 ]; do
        let top=$top-1
        parent="${stack[$top]}"
        for i in `ls "$parent"`; do
            fpath="$parent/$i"
            $callback "$fpath" # do whatever you want
            if [ -d "$fpath" ]; then
                stack[$top]="$fpath"
                let top=$top+1
            fi
        done
    done
}
 
function bfs()
{
    #if [ $# -ne 2 ]; then
        #echo "function call error: bfs callback root_dir" >&2
        #exit -1
    #fi
 
    callback=$1
    root=$2
 
    let begin=0
    let end=1
    queue[0]="$root" # root dir
 
    while [ $begin -lt $end ]; do
        for i in `ls "${queue[$begin]}"`; do
            fpath="${queue[$begin]}/$i"
            $callback "$fpath" # do whatever you want
            if [ -d "$fpath" ]; then
                queue[$end]="$fpath"
                let end=$end+1
            fi  
        done
        unset queue[$begin]
        let begin=$begin+1
    done
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值