避免语句中的if语句提高错误时,错误的bash

问题描述:

为了使我的数据架构形式我最后往往具有深层的文件夹树在那里它可以是一个有点恼人回去,并在这样转发我写了一个函数生成一个HTML在CWD的树:避免语句中的if语句提高错误时,错误的bash

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 
} 

将其更改为:

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

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

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

谢谢你的错误!我特别喜欢第二个选项,因为它规避LS“没有这样的文件或目录”的错误,而不是重定向它。 – edager

只是一个建议,采取了这一点"$(ls -b toc_* | wc -l)"和集它的可变

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

2>/dev/null是发送标准错误即任何类型的错误信息到/ dev/null的

并且还建议你总是使用[[ ]]当你正在编写一个if语句,避免像unary operator is expected