微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – shell脚本中的递归

我正在学习Linux命令,我正在练习并尝试编写一个基本的shell脚本,它使用递归列出子文件夹中的所有文件文件,如ls *.

#!/bin/bash

# list-all: one command to list them all!!!!

listit () {
        if [ -d "$1" ]
        then
                listit "$1"
        else
                echo "$1"
        fi  
}

ls | while read items; do
        listit "$items"
done

但结果显示

./list-all: line 16:  1101 Done                    ls
      1102 Segmentation fault: 11  | while read items; do
    listit "$items";
done

那是因为shell不允许递归吗?请帮帮忙,谢谢!

解决方法:

shell肯定支持递归.但是你的函数需要参数,而你传递的是stdin.除此之外,你真的不应该是parsing the output of ls.考虑一下:

listit() {
    while [ "$1" ]; do
        if [ -d "$1" ]; then
            listit "$1"/*
        else
            printf '%s\n' "$1"
        fi
        shift
    done
}

listit *

如果你真的想读stdin,你必须重写listit来做到这一点.这很棘手,因为你只得到一个标准输入,每个递归调用都会尝试拥有它.文件名是一个简单的东西,通过globbing作为参数可访问,所以我坚持这一点.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐