[英]How to implement tree command in bash/shell script?
我嘗試在 bash 中實現一些代碼,其中 output 類似於終端中的“樹”命令。
這里是:
listContent() {
local file
for file in "$1"/*; do
if [ -d $file ]; then
countSpaces $file
echo $?"Directory: $file"
listContent "$file"
elif [ -f $file ]; then
countSpaces $file
echo $?"File: $file"
fi
done
}
countSpaces() {
local space=" "
for (( i=0; i<${#$1}; i++ )); do
if [ ${file:$i:1} = "/" ]; then
space = space + space
return space
done
}
listContent "$1"
運行我給出的腳本: ./scriptName.sh directoryName 其中 scriptName 是我的腳本,directoryName 是參數,它是代碼應該從中開始的目錄的名稱。
我希望看到這樣的 output:
Directory: Bash/Test1Dir
File: Bash/Test1Dir/Test1Doc.txt
Directory: Bash/Test2Dir
Directory: Bash/Test2Dir/InsideTest2DirDir
File: Bash/Test2Dir/insideTest2DirDoc.txt
File: Bash/test.sh
但是我在完成這段代碼時遇到了一些麻煩。 有人可以幫我弄清楚為什么它不起作用以及我應該更改什么嗎?
將不勝感激。
正確而有效的實現可能看起來像:
listContent() {
local dir=${1:-.} whitespacePrefix=$2 file
for file in "$dir"/*; do
[ -e "$file" ] || [ -L "$file" ] || continue
if [ -d "$file" ]; then
printf '%sDirectory %q\n' "$whitespacePrefix" "${file##*/}"
listContent "$file" "${whitespacePrefix} "
else
printf '%sFile %q\n' "$whitespacePrefix" "${file##*/}"
fi
done
}
注意:
/
s數。 $?
除了用於跟蹤數字出口狀態的預期目的外,還可以用於其他目的。 printf %q
,以確保即使是惡意名稱(包含換行符,光標控制字符等)也能被明確打印。 如果你想要一個沒有Directory
和File
領導者的視覺表示,那么下面是一個簡單的單行代碼(包裝在 shell 函數中)。
treef() (
[ -d "$1" ] && { dir="$1"; shift; } || dir='.'
find "$dir" "$@" | sed -e 's@/@|@g;s/^\.|//;s/[^|][^|]*|/ |/g;/^[. |]*$/d'
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.