bash for循环以检查目录是否存在

bash for循环以检查目录是否存在

问题描述:

以下程序很有趣,我正尝试进入bash脚本编写.我不会使用该脚本进行备份.

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.

我正在尝试创建一个for循环,以检查数组中的用户输入(将要备份的目录)是否有效.如果输入有效,则应使用它.如果不是,则应使用默认值/home/$ USER 覆盖它.

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

这是我得到的输出(/home/michael/Downloads 是目录, notadirectory 不是)

This is the output I get (/home/michael/Downloads is a directory, notadirectory isn't)

谢谢您的时间.

在您的代码中 $ {USER_DIR [$ i]} = $ {USER_DIR [$ i]} 失败.
要分配某些内容时,应删除第一个 $ .
您的错误更早了.
您想测试目录"$ {USER_DIR [0]}" ,但是您正在测试"$ {USER_DIR [$ i]}" ,这是>

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"]}

尝试

for i in ${#USER_DIR[@]}

for ((i=0; i<${#USER_DIR[@]}; i++))