Saturday, August 17, 2013

bash中处理文件名有空格的问题 $(command ls) when file name with space

一个练习。遍历指定的目录,以树状结构显示包括子目录下的所有文件。
在bash中遍历文件用
for file in * ; do
...
done
很多教科书上用: for file in $(commmand ls *) ,但这种方法不能正确处理文件名中包含$IFS指定的分隔符,即便ls 用 --quoting-style=shell 限定也没有用。

for file in * ; 的缺点是不能处理隐藏文件或目录

完整源码如下:
#!/bin/bash

declare -r tab="---"
declare -r lead="|"

function recdir {

declare -i cbfiles=0
declare -a files 

local thistab="$2"$lead$tab
cd "$1"

# get how many files in this directory
for file in * ; do
 files[$(( cbfiles++ ))]="$file"
done

declare -i curr=0
for file in "${files[@]}" ; do
 curr=$((++curr))
 echo "$thistab$file"
 if [ -d "$file" ]; then
  space=${tab//-/' '}
  ll=""
  if [ $(( curr < cbfiles )) = 1 ]; then
   ll=$2$lead"${space}"
  else
   ll="$2 ${space}"
  fi
  recdir "$file" "$ll"
 fi
done

cd ".."
}

rootdir=${1:-.}
rootdir=${rootdir%/}

if [ -d "$rootdir" ]; then
 echo "$rootdir"
 recdir $rootdir
else
 echo "$rootdir is not a directory."
fi

unset rootdir

执行结果如下:
.
|---CRFSC_Manual.pdf
|---foo1
|---foo1~
|---p1_b.jpg
|---p1.jpg
|---p2.jpg
|---p3.jpg
|---studynote
|   |---Match Waveform Theory Notebook.odt
|   |---test.txt
|   |---whh
|       |---a.txt
|---SWIGDocumentation.pdf
|---科学和特异功能.odt

No comments:

Search This Blog