我有代碼,它從目錄和子目錄中輸出檔案和目錄。但我應該只輸出嵌套級別的檔案。我也不能使用 find 和 ls。僅使用 for 回圈進行遞回。怎么做?
#!/bin/bash
recurse() {
for i in "$1"/*;do
if [ -d "$i" ];then
recurse "$i"
elif [ -f "$i" ]; then
echo "level) $i"
fi
done
}
recurse "$1"
稱呼./script.sh /home
uj5u.com熱心網友回復:
歡迎來到 Stackoverflow。您快到了!假設您的意思是從零開始的嵌套級別,請嘗試以下操作:
#!/usr/bin/env bash
set -e -u
recurse() {
local level="${2:-0}"
for i in "$1"/*; do
if [ -d "$i" ]; then
recurse "$i" "$(( level 1 ))"
elif [ -f "$i" ]; then
echo "level $level) $i"
fi
done
}
recurse "$1"
請注意,這是通過一個狀態變數(此處為深度),這在遞回編程中很常見。默認設定為零。
要測驗這樣的樹:
$ tree
.
├── bar
├── foo
│ ├── bar
│ │ ├── hello
│ │ └── hi
│ └── me
└── script.sh
它像這樣運行:
$ ./script.sh .
level 2) ./foo/bar/yo
level 1) ./foo/me
level 0) ./script.sh
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515666.html
標籤:重击递归
下一篇:如何從字串輸入遞回創建嵌套串列
