bash中的递归
这是learning the bash shell, 3rd ed中的一个练习的改良版本。搁这儿不是显摆我做出来了,就是记录一下bash里递归怎么用。
Positional parameters就是没有named好。curdir那个变量我就懒得传了,还得处理参数,于是用了个全局的。
recls ()
{
# TODO check: only accepts 1 argument, must be a directory
# global var singletab
singletab='\t'
# global var curdir, reset
unset curdir
# start recursion
recdir 0 $@
unset singletab curdir
}
recdir ()
{
local level=$1 file
shift 1
for file in $@; do
rptprt $singletab $level
echo -e $file
if [ -d "$curdir$file" ]; then
curdir=$curdir$file/
recdir $((level+1)) $(ls $curdir)
curdir=${curdir%$file/}
fi
done
}
rptprt ()
{
# usage: prt STRING_TO_PRINT TIMES
# well, you may think we could use brace expansion to do it:
# printf "$1%.0s" {1..$2}
# but brace expansion is performed before parameter expansion, e.g.
# {1..$2} where the second parameter is 5
# will be evaluated to {1..5} insteand of 1 2 3 4 5
# because {1..$2} is an illegal brace expansion so bash just keep it as is
# then parameter expansion will make it {1..5}
# However, we can always use eval:
# printf "$1%.0s" $(eval echo {1..$myvar})
if [ $2 -gt 0 ]; then
printf "$1%.0s" $(seq $2)
fi
}
我还特意写了一个rptprt (repeat print)来重复打印。注意它极为tricky...我写了好多注释。简单来说就是和bash分析输入时,做各种工作的顺序有关。
这破程序把我折腾死了。书里有好多又臭又长的例子,我发誓再也不用Bash写超过5行的脚本了。。。Bash根本就不适合做很多事情,所以深学的价值不是很高,但又不能不懂。