shell 递归函数

2021-09-27  本文已影响0人  AppleLin_cdea

2021年9月27日18:35:44 星期一
在定义 shell 函数时,要加 local 来定义变量为函数内局部变量。

例子: 递归显示目录和子目录文件

示例代码

#!/bin/bash
# my_ls.sh

usage()
{
    echo "usage: `basename $0` <ls_dir>"
}

if [ $# -ne 1 ];then
    usage
    exit 1
fi

if [ ! -d $1 ];then
    echo ERROR: $1 is not a  directory.
    usage
    exit 2
fi

f_ls()
{
    local tmp_dir=$1
    local file=""

    echo $tmp_dir/

    for file in `ls $tmp_dir`
    do
        if [ -d $tmp_dir/$file ];then
            f_ls "$tmp_dir/$file"
        else
            echo "$file"
        fi
    done
}

f_ls $1

测试

apple$tree test
test
├── 1.txt
├── a
│   ├── a1
│   ├── a1.txt
│   └── a2.txt
├── b
│   └── b1.txt
└── c

4 directories, 4 files
apple$./my_ls.sh test
test/
1.txt
test/a/
test/a/a1/
a1.txt
a2.txt
test/b/
b1.txt
test/c/
上一篇 下一篇

猜你喜欢

热点阅读