[英]Recursive directory listing in shell without using ls
我正在尋找一個腳本,該腳本使用導出和讀取鏈接而不使用ls選項來遞歸列出所有文件。 我已經嘗試了以下代碼,但是不能達到目的。 請你幫忙。
我的代碼
#!/bin/bash
for i in `find . -print|cut -d"/" -f2`
do
if [ -d $i ]
then
echo "Hello"
else
cd $i
echo *
fi
done
這是一個簡單的遞歸函數,它會列出目錄:
list_dir() {
local i # do not use a global variable in our for loop
# ...note that 'local' is not POSIX sh, but even ash
# and dash support it.
[[ -n $1 ]] || set -- . # if no parameter is passed, default to '.'
for i in "$1"/*; do # look at directory contents
if [ -d "$i" ]; then # if our content is a directory...
list_dir "$i" # ...then recurse.
else # if our content is not a directory...
echo "Found a file: $i" # ...then list it.
fi
done
}
或者,如果使用“遞歸”,則表示您希望列表是遞歸的,並且可以接受代碼本身不做任何遞歸:
#!/bin/bash
# ^-- we use non-POSIX features here, so shebang must not be #!/bin/sh
while IFS='' read -r -d '' filename; do
if [ -f "$filename" ]; then
echo "Found a file: $filename"
fi
done < <(find . -print0)
安全地執行此操作需要使用-print0
,以便名稱之間用NUL分隔(文件名中不能存在的唯一字符;名稱中的換行符有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.