I am working on a bash script that should backup folders which users can specify. The script is just for fun, and to get into bash. I will not use it for real backup purposes.
The idea is that users can enter specific folders they want to update. After each entry, they would hit ENTER
and then type another directory into the console. After they are finished, they would press CTRL-D
. The inputs would then be saved into an array USER_DIR
. This array would then be checked to see if the directories exist. If they do exist, the entry will stay the same. If they don't exist the entry will be overwritten be a default value /home/$USER
.
I have found an interesting idea on AskUbuntu (I am using Ubuntu):
while read line
do
my_array=("${my_array[@]}" $line)
done
echo ${my_array[@]}
I have used that and tried to input multiple directories, but it only worked if the input was exactly one directory. Every time I used multiple directories as input, it defaulted to /home/$USER
. I have put echo ${my_array[@]}
on different positions in the script, and it looked as if the problem was with the delimiter, as the input was seemingly concatenated with whitespaces.
I tried to look for a way to loop through the array and change the delimiter after the input was saved. I found an interesting idea on StackOverflow:
SAVEIFS=$IFS # Save current IFS
IFS=$'\n' # Change IFS to new line
names=($names) # split to array $names
IFS=$SAVEIFS # Restore IFS
I tried it out, but it also only accepts singular input. My script looks like this at the moment:
echo "Please enter absolute path of directory for backup. Default is ""/home/$USER"
echo "You can choose multiple directories. Press CTRL-D to start backup."
# save user input into array
while read line
do
USER_DIR=("${USER_DIR[@]}" "$line")
done
SAVEIFS=$IFS # Save current IFS
IFS=$'\n' # Change IFS to new line
USER_DIR=($USER_DIR) # split to array $names
IFS=$SAVEIFS # Restore IFS
# check if user input in array is valid (directory exists)
for ((i=0; i<${#USER_DIR[@]}; i++))
do
if [[ -d "${USER_DIR[$i]}" ]]; then
# directory exists
USER_DIR=("${USER_DIR[@]}")
echo "${USER_DIR[@]}" # for debugging
else
# directory does not exist
USER_DIR=("/home/$USER")
echo "${USER_DIR[@]}" # for debugging
fi
done
# show content of array
echo "Backups of the following directories will be done:"
for i in "${USER_DIR[@]}"; do echo "$i"; done
Any help would be greatly appreciated. Thank you for your time.