2017-04-03 46 views
0

我正在爲練習編寫一個bash shell腳本,但似乎無法修復它的行爲。該腳本將一組文件和目錄複製到給定的備份目錄$ path,並將其壓縮爲.tar.gz文件。爲什麼這個shell腳本在不讀`case`的情況下退出?

如果說名爲.tar.gz文件已經存在使用備份目錄($ date_value.tar.gz)的命名模式,並具有根據答案特定情況下我的工作應該檢查迭代。預計該腳本現在將從主項目目錄運行。

以下代碼是出錯的部分。

if [ -f "$path/$date_value.tar.gz" ] ; then 

    echo "A $date_value.tar.gz directory already exists." 

    read -p "Do you wish to update directory ? (Y/N)" 

    echo # Moves to new line; for user experience purpose only 

    case $REPLY in 

     # Case when user wrote "Y" or "y" as in Yes 
     " [[ $REPLY =~ ^[Yy]$ ]] ") 

      # Extract archive 
      tar xf "$path/$date_value.tar.gz" 

      # Synchronise directories 
      rsync --update -raz --progress \ 
        --include="$current_path${files_array[@]}" "$path/$date_value" \ 
        --exclude="*" 

    exit 0; 
;; 

     # Case when user wrote anything else 
     " [[ $REPLY =~ ^[*]$ ]] ") 

      echo "Script didn't make any change and stopped itself." 

    exit 1; 
esac 

# Else if backup directory doesn't exist yet 
else 

    # Make a directory using the date 
    mkdir "$path/$date_value" 

    # Loops over the whole array and copies files/directories 
    # recursively to given directory with current rights 
    for i in ${files_array[@]}; do 
      cp -ar ${i} /home/robin/backup/by_date/"$date_value"/ 
    done 

    # Goes to backup directory 
    cd "$path" 

    # Compress backup directory into tarball AND(=&&) removes it if successfull 
    tar cfM "$date_value.tar.gz" "$date_value" && rm -Rf "$date_value" 

fi 

bash -x模式下運行,我看到它繼續如預期直到case $REPLY in線,然後突然停止,不通過的情況下運行。我在最後一次關閉fi之後放了一個exit 1作爲測試,並且可以確認腳本跳過case並停止,因爲沒有進一步的說明。

那裏出了什麼問題,爲什麼它開船case

文檔用來寫這樣的代碼:

上運行Debian,其中bash作爲終端。

+4

...因爲案件都應該成爲球體。 –

+1

將腳本粘貼到http://www.shellcheck.net/以修復語法錯誤! – Inian

+0

看看你發佈的第一個鏈接的第二個灰色框,關於流量控制。該示例將變量與1,2,3(數字)進行比較。後續的例子更加完整,並且它們從不使用錯綜複雜的'[[$ REPLY ...]]''。你寫得很好,工作很好,但你應該閱讀你自己發佈的鏈接! – linuxfan

回答

2

錯誤:

" [[ $REPLY =~ ^[Yy]$ ]] ") 

正確:

[Yy]) 

有在OP代碼其他錯誤,但與開始......

+2

在glob中'^'會匹配一個文字'^',而不是行首。試試'Y | y)' –

+0

@WilliamPursell,修復並感謝您所需的修復。 – agc

+0

@WilliamPursell指出,'^'與文字^相匹配,我的情況仍然被忽略。改成'Y | y)'和'*)'確實有效。謝謝你們倆 ! – Apweleleh

相關問題