我有一個名為 func1 的函式。當傳遞一個引數時,它將生成一個專案串列。我需要將這些專案中的每一個作為引數傳遞給 func1 等等,直到沒有更多可以傳遞。前任。
func1 <arg> | while read item
do
func1 item | while read item1
do
func1 item1 <--- how to do this recursion?
done
done
只需要一些實作思路。謝謝
uj5u.com熱心網友回復:
試試這個有點做作的Shellcheck -clean 演示程式:
#! /bin/bash -p
shopt -s dotglob nullglob
# Print the paths to the tree of directories rooted at the given directory
function dirtree
{
local -r dir=$1
printf '%s\n' "$dir"
local entry subdir
for entry in "$dir"/*; do
[[ -L $entry ]] && continue
[[ -d $entry ]] && printf '%s\0' "$entry"
done \
| while IFS= read -r -d '' subdir; do
dirtree "$subdir"
done
return 0
}
dirtree ~
shopt -s設定一些 Bash 配置:dotglob使 glob 能夠匹配以 . 開頭的檔案和目錄.。nullglob當沒有匹配項時,使 glob 擴展為空(否則它們擴展為 glob 模式本身,這在程式中幾乎從不有用)。
- 基本情況沒有顯式處理,因為當您降低目錄結構時,您可以保證最終到達沒有子目錄的目錄。符號鏈接可能會導致目錄結構中的回圈,因此
[[ -L $entry ]] && continue代碼中的行是為了停止遵循符號鏈接。
該功能是人為設計的,因為while回圈和管道是不必要的。一個更清潔、更簡單、更有效的替代方案是:
# Print the paths to the tree of directories rooted at the given directory
function dirtree2
{
local -r dir=$1
printf '%s\n' "$dir"
local entry
for entry in "$dir"/*; do
[[ -L $entry ]] && continue
[[ -d $entry ]] && dirtree2 "$entry"
done
return 0
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487723.html
上一篇:SIGSEGV訪問指向二叉樹左節點的指標,即使指標已初始化
下一篇:在這種情況下如何避免顯式遞回?
