readdir
是一個用于讀取目錄內容的函數,通常在 shell 腳本中使用。它可以列出指定目錄中的所有文件和子目錄。以下是一個簡單的示例,展示了如何在 shell 腳本中使用 readdir
函數:
#!/bin/bash
# 定義一個函數,用于讀取目錄內容
readdir() {
for file in "$1"/*; do
if [ -d "$file" ]; then
echo "Directory: $file"
elif [ -f "$file" ]; then
echo "File: $file"
fi
done
}
# 調用函數,傳入要讀取的目錄路徑
readdir "/path/to/your/directory"
將此腳本保存為 list_directory_contents.sh
,并確保它具有可執行權限(使用 chmod +x list_directory_contents.sh
)。然后,通過運行 ./list_directory_contents.sh
來執行腳本。
請注意,您需要將 /path/to/your/directory
替換為您要讀取的實際目錄路徑。
此外,您還可以使用 find
命令來實現類似的功能。以下是一個使用 find
的示例:
#!/bin/bash
# 定義一個函數,用于讀取目錄內容
readdir() {
find "$1" -type d -exec echo "Directory: {}" \;
find "$1" -type f -exec echo "File: {}" \;
}
# 調用函數,傳入要讀取的目錄路徑
readdir "/path/to/your/directory"
這個腳本的功能與前一個示例相同,但使用了 find
命令來查找目錄中的文件和子目錄。同樣,確保將 /path/to/your/directory
替換為您要讀取的實際目錄路徑。