我正在爲練習編寫一個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
?
文檔用來寫這樣的代碼:
- 流量控制:http://linuxcommand.org/wss0120.php
- Check if a directory exists in a shell script
- 測試建築:http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS
- 測試建築使用[[]]具體操作符:Bash regex =~ operator
在上運行Debian,其中bash
作爲終端。
...因爲案件都應該成爲球體。 –
將腳本粘貼到http://www.shellcheck.net/以修復語法錯誤! – Inian
看看你發佈的第一個鏈接的第二個灰色框,關於流量控制。該示例將變量與1,2,3(數字)進行比較。後續的例子更加完整,並且它們從不使用錯綜複雜的'[[$ REPLY ...]]''。你寫得很好,工作很好,但你應該閱讀你自己發佈的鏈接! – linuxfan