1. 程式人生 > >Mac shell遍歷資料夾 刪除.svn

Mac shell遍歷資料夾 刪除.svn

為了寫個遍歷檔案的指令碼,找了好多網上的參考,終於沒問題了,就總結一下。

for fileName in *; do
		
		if [[ -d $fileName ]]; then
			echo $fileName;
		elif [[ ! -e $fileName ]]; then
				echo $fileName not exist
		fi
		
	done

開始用這種方法遍歷目錄下的檔案,後來發現*只能找到可見檔案,找不到隱藏的檔案,而我要處理的資料夾可能會是隱藏檔案,

就又在網上找到了一種方法:

files=`ls -A`
	for fileName in $files; do
		
		if [[ -d $fileName ]]; then
			echo $fileName;
		elif [[ ! -e $fileName ]]; then
				echo $fileName not exist
		fi
		
	done
這種方法可以在/bin/bash 下用 ,/bin/zsh 下 ls -A 返回的不是陣列,無法遍歷,沒找到原因,由於我開始預設用的是zsh,坑了我好大一會找原因,這可能就是兩種shell的不同吧

雖然能遍歷了,但是發現個別目錄進不去,因為檔名有空格,這個通常的毛病網上確實很多相關答案,可是在我的腳本里不能很好工作,不知道是不是解決這個問題的人和我的環境不一樣。我是Mac平臺/bin/bash,  這個 IFS=$(echo -en "\n\b") 更改IFS的放到我的腳本里反而把我沒有空格的檔名都給拆開了,找了半天找到 用 IFS=$'\n' (單引號) 解決了,下面就附上我隨便寫的遞迴刪除所有目錄下的 .svn指令碼:

#!/bin/bash
# rm svn file

echo $1


if [[ ! -d $1 ]]; then
	echo "not dir"
	return
fi

SAVEIFS=$IFS;
IFS=$'\n'
rmDirSvn(){
	
	cd $1;
	
	countF=`ls -A | wc -l`
	if [[ $countF -eq 0 ]]; then
		cd ./../
		echo $1 is null
		return;
	fi
	countF=`find . -name ".svn" -maxdepth 1`
	if [[ -n $countF ]]; then
		rm -rf .svn
	fi
	
	
	files=`ls -A`
	for fileName in $files; do
		
		if [[ -d $fileName ]]; then
			rmDirSvn $fileName;
		elif [[ ! -e $fileName ]]; then
				echo $fileName not exist
		fi
		
	done
	
	cd ./../
}

rmDirSvn $1;
IFS=$SAVEIFS
執行的時候只需要 ./rmSvn.sh testSvn 就能刪除testSvn目錄下的所有.svn目錄了

其實上面這麼多程式碼和下面這幾行是等價的

IFS=$'\n'
files=`find . -name ".svn"`
for f in $files;do
rm -rf $f
或者一行命令也足已搞定:
find . -name ".svn" -exec rm -rf {} \;
這條命令的好處就是不用設定IFS也能處理空格的檔案
以上是我參考了許多網友的經驗,再次表示感謝。