问题
The following program is just for fun, I am trying to get into bash scripting. I am not going to use the script for doing backups.
I am trying to create a for loop to check if user input (directories that will be backed up) in an array are valid. If input is valid, it should be used. If not, it should be overwritten with a default value /home/$USER
.
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."
read USER_DIR
# save user input into array
while read line
do
USER_DIR=("${USER_DIR[@]}" $line)
done
# check if user input in array is valid (directory exists)
for i in ${USER_DIR[@]}
do
if [[ -d "${USER_DIR[$i]}" ]]; then
# directory exists
${USER_DIR[$i]}=${USER_DIR[$i]}
else
# directory does not exist
${USER_DIR[$i]}="/home/$USER"
fi
done
# show content of array (check if for loop works)
echo "Backups of the following directories will be done:"
for i in ${USER_DIR[@]}; do echo $i; done
This is the output I get (/home/michael/Downloads
is a directory, notadirectory
isn't)
Thank you for your time.
回答1:
In your code ${USER_DIR[$i]}=${USER_DIR[$i]}
fails.
You should remove the first $
when you want to assign something.
Your error is earlier.
You want to test the directory "${USER_DIR[0]}"
, but you are testing "${USER_DIR[$i]}"
, and this is
${USER_DIR["/home/michael/Downloads"]}
Try
for i in ${#USER_DIR[@]}
or
for ((i=0; i<${#USER_DIR[@]}; i++))
来源:https://stackoverflow.com/questions/61430278/bash-for-loop-to-check-if-directory-exists