mardi 15 novembre 2016

Avoid statements inside if statements raising errors when false bash

To keep my data in structured form I often end up having deep folder-trees where it can be a little annoying going back and forward in so I wrote a function to generate an html tree of the cwd:

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

}

The problem arose when I wrote a follow up function to remove old folder-tree files, specifically in the first expr of [ "$(ls -b toc_* | wc -l)" -gt "0" ] which gives an error when no files are found even though it's value is correctly set to 0, which should make it skip the if statement (right?). The code works as intended, but error messages are usually not a sign of good code, so was hoping that someone might be able to suggest improvements?

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 
}

Aucun commentaire:

Enregistrer un commentaire