[英]How can I fix this Bash function to start at a specified path and recursively list its subdirectories and the subdirectories of those etc
我正在嘗試編寫一個腳本來搜索目錄及其子目錄等以查找與給定正則表達式匹配的文件。 所以我開始嘗試編寫一個函數來首先獲取目錄和子目錄。 出於某種原因,它目前似乎只獲取指定目錄中的第一個子目錄。
這是函數:
getDirs() {
cd "$1"
for i in *; do
if [ -d "$i" ]; then
echo "dir: $PWD/$i"
getDirs "$i"
fi
done
}
getDirs $path
任何想法如何解決這一問題?
如果您需要正則表達式來搜索文件名,請嘗試使用find執行此操作:
regex="YourRegexPattern"
find "$1" -type f -regextype posix-egrep -regex "$regex"
如果您想獲取所有目錄/子目錄:
find . -type d
這應該可以做到,盡管find
更有效。
getDirs() {
for i in "$1"/*; do
if [ -d "$i" ]; then
echo "$i"
getDirs "$i"
fi
done
}
當然,那只是因為您在循環后永遠不會回到上一個目錄。 你可以把所有東西都放在一個子shell中:
getDirs() {
(
cd "$1"
for i in *; do
if [[ -d "$i" ]]; then
echo "dir: $PWD/$i"
getDirs "$i"
fi
done
)
}
getDirs $path
或者在循環后將當前目錄保存到cd
到它,因此:
getDirs() {
local currentdir=$PWD
cd "$1"
for i in *; do
if [[ -d "$i" ]]; then
echo "dir: $PWD/$i"
getDirs "$i"
fi
done
cd "$currentdir"
}
getDirs $path
或者其他......我想你現在知道你的錯誤在哪里了!
您還應該檢查您的cd
是否可以使用,例如cd "$1" || <do something as the cd failed>
cd "$1" || <do something as the cd failed>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.