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>