除了 PHP 之類的語言,shell 腳本也能勝任目錄遍歷。以下提供兩種寫法:一種靠 find 搭配迴圈,另一種則自行定義遞迴函式。
#!/bin/bash
echo "please input the directory:"
read cdir
for dir in $(find $cdir -type d); do
echo change to $dir
cd $dir
ls
echo "----------"
done
cd $cdir
find -type d 會列出所有子目錄,迴圈逐個切換並列出內容,程式碼短而好懂。
#!/bin/sh
read -p "Input Path:" SPATH
FILELIST() {
filelist=`ls $SPATH`
for filename in $filelist; do
if [ -f $filename ]; then
echo File: $filename
elif [ -d $filename ]; then
cd $filename
SPATH=`pwd`
echo $SPATH
FILELIST
cd ..
else
echo "$SPATH/$filename is not a common file."
fi
done
}
cd $SPATH
FILELIST
echo "Done."
這個版本遇到目錄就呼叫自己,因此能深入任意層級,同時用 -f 與 -d 分辨檔案與目錄。
兩者取捨:想快速掃一輪用 find 版本;需要對每個檔案做額外處理、或想練習遞迴思維,就用函式版本。若只是單純列出全部檔案,其實 find $SPATH -type f 一行就足夠了。