簡體   English   中英

如何在 bash/shell 腳本中實現樹命令?

[英]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數。
  • 我們引用了所有參數擴展,除了在有限數量的上下文之一中隱式避免了字符串拆分和glob擴展之外。
  • 我們避免嘗試使用$? 除了用於跟蹤數字出口狀態的預期目的外,還可以用於其他目的。
  • 每當出現不受控制的數據(例如文件名)時,我們都會使用printf %q ,以確保即使是惡意名稱(包含換行符,光標控制字符等)也能被明確打印。

如果你想要一個沒有DirectoryFile領導者的視覺表示,那么下面是一個簡單的單行代碼(包裝在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM