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

被折叠的 条评论
为什么被折叠?



