0
点赞
收藏
分享

微信扫一扫

Linux Bash Shell学习(十):流程控制——for


  本文也即《Learning the bash Shell》3rd Edition的第五章Flow Control之读书笔记之二,但我们将不限于此。flow control是任何编程语言中很常用的部分,也包括了bash。在这里,我们将继续学习他们。

  和C不一样的是,在shell中是匹配list中的元素,因此非常适合用于命令的参数,文件列表。for格式如下:

for name  [in list ] 
 do 
     statements that can use  $name... 
 done

  我们通过下面的例作进一步学习。一共设置了三个例子

# Test for the bash loop : for method 
 # 
 # Test 1: 显示$PATH中各个具体路径的详细信息function getpath 
 { 
     # 设置分割符号为“:”,缺省为空格 
     IFS=:      # for测试,其中ls -ld中的-d表示之显示目录的属性,不显示目录下属的文件。 
     for dir in $PATH 
     do 
         ls -ld $dir 
     done 
 } # 通常$PATH中包含~/bin目录,一般不存在,在ls的显示中会报告错误,需要挑出进行处理。同时我们增加一个空的元素来进行分析。 
 function getpath1 
 { 
     path=$PATH:: 
     echo check : $path 
     IFS=:     for dir in $path 
     do 
         # 如果是空元素,将其转换为当前目录。 
         if [ -z $dir ] ; then    dir=. ; fi 
         if ! [ -e $dir ]; then 
             echo "$dir is not exist!" 
         elif ! [ -d $dir ]; then 
             echo "$dir is not a directory!" 
         else 
             ls -ld $dir 
         fi 
     done 
 } #echo 'run getpath' 
 #getpath echo 'run getpath1' 
 getpath1 # Test 2 显示指定文件的是否是有效文件名 
 function finfo 
 { 
     if ! [ -e "$1" ]; then 
         echo "$1 is not an availble file." 
     else 
         echo "$1 is a file." 
     fi 
 } echo 'run fileinfo' 
# 如果命令没带参数,即list为空,则不执行for里面的代码 
 for filename in $@; do 
     echo "in for loop..." 
     finfo "$filename" 
 done

  下面是一个递归的例子,我们希望将目录下的文件也显示出来。根据层次结构,下一级比上一级向后挪一个tab。

# Test 3: 显示目录下的文件,采用递归方式 。showdirfile 表示显示所在目录的所有文件,如果也是目录,递归执行。为了记录方便,将注释加载命令行后面,注意这只是为了阅读方便,而不是shell应有的语法。 
 function showdirfile 
 {  
       #step1 :只有是有效目录文件,才search     
       if [ -d $1 ] ; then  
         #step2 ,比上一级后退tab,记录前面tab的字符 
         currenttab+="/t" 
         #$(command <command>)  用于给出command的输出结果,作为字符串。 
         #step 3 :搜索ls <dir_name>所显示的entry,如果是文件,显示,如果是字符串显示,并在后面加上"/",表明是目录,使用递归,检索该目录下的文件。 
         for file in $(command ls $1); do 
             echo -e -n ${currenttab}$file 
             #step 4: 文件的含路径名字为$1/$file,由于我们没有采用cd $file,即没有进入该目录进行访问,因此要记录path,如果是目录,用dir记录下这个子目录的名字 
             if [ -d $1/$file ]; then 
                 echo "/" 
                 showdirfile $1/$file 
             else 
                 echo 
             fi 
         done 
         #step2 ,执行完推出,恢复上一级的前面的tab字符串,即去掉最后的/t。 
         currenttab=${currenttab%"/t"} 
     # end of step 1 
     fi 
 } 
# 之前设置了IFS,会使得ls的输出不是以空格为分割,异常,需要重置它 
unset IFS 
 echo 'run file architechture' 
 showdirfile ${1:-"~"}


举报

相关推荐

0 条评论