Linux shell递归遍历目录

Linux shell递归遍历目录

Linux上可以通过如下shell脚本遍历指定目录:

#!/bin/bash

function list_file()
{
    local last_dir=$(pwd)
    if [[ $# -ne 1 ]]; then
        echo "usage `basename $0` <directory> "
    fi
    
    cd $1
    for tmpfile in $(ls)
    do
        if [ -d $tmpfile ]; then
            echo "directory: $tmpfile"		
            list_file $tmpfile
        else
            echo "file: $tmpfile"
        fi
    done
    cd $last_dir
}

if [[ $# -ne 1 ]]; then
    echo "usage `basename $0` <directory> "
    exit
fi

list_file $1

执行效果如下:

yuxuecheng@linux:~/shellSource> ls -AlR ../bin/
../bin/:
total 32
-rwxr-xr-x 1 yuxuecheng users  277 Mar 19  2015 mklink.sh
-rwxr-xr-x 1 yuxuecheng users 5001 Mar 19  2015 modify_ini.sh
drwxr-xr-x 3 yuxuecheng users 4096 Mar 19  2015 test
-rw-r--r-- 1 yuxuecheng users   72 Mar 19  2015 test.ini
-rw-r--r-- 1 yuxuecheng users    0 Mar 18  2015 test.txt
-rwxr-xr-x 1 yuxuecheng users  686 Mar 19  2015 unlink_symbol.sh
-rwxr--r-- 1 root       root   902 Feb 28  2015 vm_init_para.ini
-rw-r--r-- 1 yuxuecheng users  922 Mar 19  2015 vm_init_para.ini.temp

../bin/test:
total 4
drwxr-xr-x 2 yuxuecheng users 4096 Mar 19  2015 test2

../bin/test/test2:
total 0
yuxuecheng@linux:~/shellSource> ./list_file.sh ../bin/
file: mklink.sh
file: modify_ini.sh
directory: test
directory: test2
file: test.ini
file: test.txt
file: unlink_symbol.sh
file: vm_init_para.ini
file: vm_init_para.ini.temp
yuxuecheng@linux:~/shellSource> 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值