I am writing a bash
shell script for practice, but can't seem to fix its behavior. The script copies an array of files and directories into a given backup directory, $path, and compresses it to a .tar.gz file.
The iteration I'm working on should check if said .tar.gz file already exists using the naming pattern for backup directory ($date_value.tar.gz), and has specific cases depending on the answer. The script is expected to be ran from main project directory for now.
The following code is the part that goes wrong.
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
When run in bash -x
mode, I see that it proceeds as expected until the case $REPLY in
line, then suddenly stops without running through the case. I put an exit 1
as a test after the last closing fi
and can confirm the script simply jumps past case
and stops, since there are no further instructions.
What is going wrong in there, and why is it ditching the case
?
Documentation used to write this code:
- Flow control : http://linuxcommand.org/wss0120.php
- Check if a directory exists in a shell script
- Test building : http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS
- Test building using [[ ]] specific operators : Bash regex =~ operator
Run on Debian, with bash
as terminal.