2016-11-15 52 views
0

爲了使我的數據架構形式我最後往往具有深層的文件夾樹在那裏它可以是一個有點惱人回去,並在這樣轉發我寫了一個函數生成一個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 
} 

回答

0

將其更改爲:

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

另一個稍微更具可讀性和更好的方法是(剝離不必要的引號):

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

謝謝你的錯誤!我特別喜歡第二個選項,因爲它規避LS「沒有這樣的文件或目錄」的錯誤,而不是重定向它。 – edager

0

只是一個建議,採取了這一點"$(ls -b toc_* | wc -l)"和集它的可變

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

2>/dev/null是發送標準錯誤即任何類型的錯誤信息到/ dev/null的

並且還建議你總是使用[[ ]]當你正在編寫一個if語句,避免像unary operator is expected