簡體   English   中英

如何通過腳本列出Bash中的目錄和文件?

[英]How to list directories and files in a Bash by script?

我想列出目錄樹,但是我必須為其編寫腳本,並且由於參數腳本應采用基本目錄的路徑。 清單應從此基本目錄開始。

輸出應如下所示:

Directory: ./a
File: ./a/A
Directory: ./a/aa
File: ./a/aa/AA
Directory: ./a/ab
File: ./a/ab/AB

因此,我需要從基本目錄中為該基本目錄中的每個目錄和文件打印路徑。

更新

運行腳本,我應該在終端中鍵入以下內容:“。\\ test.sh / home / usr / Desktop / myDirectory”或“。\\ test.sh myDirectory”-因為我是從桌面級別運行test.sh的。 現在,該腳本應從/ home / usr / Dekstop / myDirectory級別運行”

我的test.sh文件中有以下命令:

find . | sed -e "s/[^-][^\/]*\//  |/g"

但這是命令 ,而不是外殼程序代碼,並打印輸出,如下所示:

DIR: dir1
    DIR: dir2
      fileA
    DIR: dir3
    fileC
fileB

如何為基本目錄中的每個目錄或文件打印基本目錄中的路徑? 有人可以幫我解決嗎?

不清楚你想要什么,

find . -type d -printf 'Directory: %p\n' -o -type f -printf 'File: %p\n'

但是,查看目錄的子樹,我發現更有用

find "$dirname" -type f

要回答評論,也可以使用遞歸函數在純bash(內置而無需外部命令)中完成。

rec_find() {
    local f
    for f in "$1"/*; do
        [[ -d $f ]] && echo "Directory: $f" && rec_find "$f"
        [[ -f $f ]] && echo "File: $f"
    done
}

rec_find "$1"

您可以使用tree命令。 -L表示最大深度。 例子:

tree
.
├── 1
│   └── test
├── 2
│   └── test
└── 3
    └── test

3 directories, 3 files

要么

tree -L 1
.
├── 1
├── 2
└── 3

3 directories, 0 files

使用以下代碼創建test.sh 在這里,您正在讀取系統變量$ 1中的命令行參數,並提供了用於查找命令的參數。

#!/bin/bash #in which shell you want to execute this script

find $1 | sed -e "s/[^-][^\/]*\//  |/g"

現在如何運作:-

./test.sh /home/usr/Dekstop/myDirectory #you execute this command

此處,命令行參數將分配給$ 1。 您可以使用$ 1到$ 9的多個參數,此后必須使用shift命令。 (您將在線獲得更多詳細信息)。

所以您的命令將是:

#!/bin/bash #in which shell you want to execute this script

find /home/usr/Dekstop/myDirectory | sed -e "s/[^-][^\/]*\//  |/g"  

希望這會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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