2017-05-08 114 views
1

我想在bash中编写递归脚本,它接收作为参数的单个路径并打印以此路径为根的目录树的深度。递归函数返回目录深度

这是list_dirs.sh脚本:

ls -l $dir | grep dr..r..r.. | sed 's/.*:...\(.*\)/\1/' 

这是isdir.sh脚本:

if [ -d $1 ]; then 
echo 1 
elif [ -e $1 ]; then 
echo 0 
else 
echo -1 
fi 

他们都工作良好。

这是脚本dir_depth.sh,我写不工作:

if [ $# -eq 0 ]; then 
    echo "Usage: ./dir_depth.sh <path>" 
    exit1 
fi 

x=`source isdir.sh $1` 
if [ $x -eq -1 ]; then 
    echo "no such path $1" 
fi 
dir=$1 
maxD=0 
dirs=`source list_dirs.sh` 
for f in $dirs 
do 
    if [ $x -ne 0 ]; then 
    x=`dir_depth.sh $f` 
    if [ "$x" -eq "$maxD" ]; then 
     maxD=x; 
    fi 
    fi 
    echo $f 
done 
echo $((maxD++)) 

我真的很新的bash脚本,我不知道如何调试或什么是错在我的脚本。

+0

编辑您的Q可包括你需要处理的目录,并从你的脚本需要输出的一个样本。否则,我们必须猜测; - /,对吗?在每行代码/数据/错误消息的前面使用4个空格,或者高亮显示一段文本,并使用编辑框左上角的格式化工具将其格式化为代码/数据/输出。祝你好运。 – shellter

回答

1

缺少一些项目有:

  1. 如果你有一个目录parent/child/和运行list_dirs.sh parent/,它将输出child。然后尝试在当前目录中查找child/而不是parent/child/

  2. 你为调试目的做echo $fecho $((maxD++))返回结果。他们彼此困惑。使用>&2将错误和调试消息写入stderr。

  3. echo $((maxD++))是一个相当于return x++的经典错误。你返回数字,然后增加一个不再使用的变量。

  4. [ "$x" -eq "$maxD" ]是没有意义的。由于您正在尝试查找最大值,因此请使用-ge

这里的dir_depth.sh这些变化的地方:

if [ $# -eq 0 ]; then 
    echo "Usage: ./dir_depth.sh <path>" >&2 
    exit 1 
fi 

x=`source ./isdir.sh $1` 
if [ $x -eq -1 ]; then 
    echo "no such path $1" >&2 
fi 
dir=$1 

dirs=`source ./list_dirs.sh` 
maxD=0 
for f in $dirs 
do 
    if [ $x -ne 0 ]; then 
    x=`./dir_depth.sh "$1/$f"` 
    if [ "$x" -ge "$maxD" ]; then 
     maxD="$x"; 
    fi 
    fi 
    echo $f >&2 
done 
echo $((maxD+1)) 
+0

为什么你会像这样在循环中传输当前目录:“$ 1/$ f”? 当你在递归中调用脚本...你为什么需要$ 1? – epsilon

+0

这是第一点。尝试使用'mkdir -p one/two'在对方内创建两个目录。然后'ls one'将显示'two',但是'ls two'会表示找不到。您必须合并根目录和子目录 –