用shell寫的遞迴遍曆目錄的指令碼,指令碼實現遞迴遍曆指定目錄,列印目錄下的檔案名稱。
執行個體1:
複製代碼 代碼如下:
#!/bin/sh
function scandir() {
local cur_dir parent_dir workdir
workdir=$1
cd ${workdir}
if [ ${workdir} = "/" ]
then
cur_dir=""
else
cur_dir=$(pwd)
fi
for dirlist in $(ls ${cur_dir})
do
if test -d ${dirlist};then
cd ${dirlist}
scandir ${cur_dir}/${dirlist}
cd ..
else
echo ${cur_dir}/${dirlist}
fi
done
}
if test -d $1
then
scandir $1
elif test -f $1
then
echo "you input a file but not a directory,pls reinput and try again"
exit 1
else
echo "the Directory isn't exist which you input,pls input a new one!!"
exit 1
fi
執行個體2:遞迴讀取目錄及其子目錄
複製代碼 代碼如下:
#! /bin/bash
function read_dir(){
for file in `ls $1`
do
if [ -d $1"/"$file ] //注意此處之間一定要加上空格,否則會報錯
then
read_dir $1"/"$file
else
echo $1"/"$file
fi
done
}
#測試目錄 test
read_dir test
這樣給test.sh加上執行許可權即可執行
複製代碼 代碼如下:
chmod +x test.sh
sh test.sh
到此即可通過傳遞參數來讀取目錄檔案了。
執行個體3:
複製代碼 代碼如下:
遞迴實現各個子目錄孫目錄......
#!/bin/bash
#modify.func
doit() //處理目前的目錄下的非目錄檔案,忽略目錄檔案
{
oldname=`ls | grep "$1$"`
for name in $oldname
do
if [ -d "$name" ]
then :
else
basename=`echo $name | awk -F "." '{print $1}'`
newname="$basename$2"
echo -e "$PWD/$name\t\t$newname"
mv $name $newname
count=`expr ${count} + 1`
fi
done
return 0
}
do_recursive() //從目前的目錄開始,遞迴處理各目錄
{
doit $1 $2
for filename in `ls`
do
if [ -d "$filename" ]
then
cd $filename
do_recursive $1 $2
cd ..
fi
done
return 0
}
modify() //處理目前的目錄,並報告結果,這個相當於主函數,也可以直接調用do_recursive
{
PARAMS=2
if [ $# -ne $PARAMS ]
then
echo "usage: mv_to .suf1 .suf2"
return 1
fi
count=0
do_recursive $1 $2
echo "complete! $count files have been modified."
return 0
}