如果语句在false bash时引发错误,请避免使用语句

时间:2016-11-15 23:13:51

标签: bash if-statement error-handling

为了保持我的数据结构化形式,我经常最终拥有深层文件夹树,在这里可能会有点烦恼,所以我写了一个函数来生成cwd的html树:

function toc_date {

   # Get the date in _YYYY-MM-DD format
   D=`date +_%F`

   # Build the tree, -H flag to output as HTML, 
   # . to use current dir in <a href> link

   tree -H . >> toc$D.html

}

当我编写一个后续函数来删除旧的文件夹树文件时出现问题,特别是在[ "$(ls -b toc_* | wc -l)" -gt "0" ]的第一个expr中,即使它的值被正确设置为0,也会在没有找到文件时发出错误,这应该让它跳过if语句(对吧?)。代码按预期工作,但错误消息通常不是良好代码的标志,所以希望有人能够提出改进建议吗?

function old_stuff {

   # Number of lines i.e. files matching toc_*   
   if [ "$(ls -b toc_* | wc -l)" -gt "0" ]  
   then 
       # Show files/directories so we don't remove stuff unintended    
       ls toc_*

       while true; do
               read -p "Do you wish to remove old TOCs? [Y/n]" yn
               case $yn in
                   [Nn]* ) break;;
                   [Yy]* ) rm toc_*; break;;
                   * ) echo "Please answer yes or no.";;
               esac
        done
   fi
   # Go ahead and generate the html tree 
   toc_date 
}

2 个答案:

答案 0 :(得分:0)

将其更改为:

if [ "$(ls -b toc_* 2>/dev/null | wc -l)" -gt "0" ]

另一种稍微更具可读性和更好的方法是(剥离不必要的引号):

if [ $(ls | grep -c '^toc_') -gt 0 ]

答案 1 :(得分:0)

只是一个建议,将其取出"$(ls -b toc_* | wc -l)"并将其设置在变量

fileCount=$(ls -b toc_* 2>/dev/null | wc -l)

2>/dev/null是将stderr,即任何类型的错误消息发送到/ dev / null

同样建议您在编写if语句时始终使用[[ ]],以避免unary operator is expected

等错误