作業九: listing a directory recursively
•建立一個 shell 執行檔, 名為 showdir, 可印出 類似用 tree -F 所得的結果.
若檔案為一目錄, 則在檔名後加 '/'
若檔案為一 symbolic link, 用箭頭顯示. 如上圖所示.
若目錄無法讀取內容, 則略過其以下的內容, 即只顯示目錄名字.
請勿用 find, du 或其他指令先得到一個 tree.
$./showdir /var/tmp/exer9-test-dir
exer9-test-dir/
|---city/
| |---lapula --> ../sky/temple/utopia
| `---rome
|---dogs/
`---sky/
|---birds
|---mountains
`---temple/
|---asking
`---utopia
$ tree -F /var/tmp/exer9-test-dir
/var/tmp/exer9-test-dir
|-- city/
| |-- lapula -> ../sky/temple/utopia
| `-- rome
|-- dogs/
`-- sky/
|-- birds
|-- mountains
`-- temple/
|-- asking
`-- utopia
4 directories, 6 files
$
解答:
#!/bin/bash
olddir=$PWD
dirdepth=0
function is_last_file {
local flag
let flag=${ary[dirdepth]}-1
if [ $flag -eq 0 ]; then #last file
ch="\\" #as \---
else
ch="|" #as |---
fi
}
function print_file {
is_last_file #check this file is last?
case "$1" in
-D) printf "$ch---$2/\n"
;; #file is directory
-L) printf "$ch---$file --> "
ls -l $file | awk '{ print $11 }'
;; #file is link
-F) printf "$ch---$file\n" #normal file
;; #file is normal file
esac
let ary[dirdepth]=ary[dirdepth]-1
}
function check_file_type {
if [ $dirdepth -gt 0 ]; then
for ((i=0; i<=dirdepth-1; i++)); do
if [ ${ary[i]} -ne 0 ]; then
printf "| " #print | & 3 space
else
printf " " #print 4 space
fi
done # for END
fi
if [ -d "$file" ]; then
print_file -D $file #directory
else
if [ -L $file ]; then
print_file -L $file #symbolic link
else
print_file -F $file #normal file
fi
fi
}
function listfiles {
cd "$1";
f_count=`ls -l | wc -l` #calc total files
let f_count=f_count-1
ary[dirdepth]=$f_count
if [ $f_count -ne 0 ]; then # if dir is empty then exit
for file in *; do
check_file_type $file #call sub
if [ -d "$file" ]; then
let dirdepth=$dirdepth+1
listfiles "$file"
cd ..;
fi
done #for END
fi
let dirdepth=$dirdepth-1
}
#-----Main Program 2017/12/06 update-----
#d=$1
#echo "${d##*/}/"
echo "$(basename "$1")/"
listfiles "$1"
執行結果:
沒有留言:
張貼留言