【发布时间】:2020-08-09 07:40:26
【问题描述】:
下面的程序只是为了好玩,我正在尝试进入 bash 脚本。我不会使用脚本进行备份。
我正在尝试创建一个 for 循环来检查数组中的用户输入(将要备份的目录)是否有效。如果输入有效,则应使用它。如果不是,则应使用默认值/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 不是)
感谢您的宝贵时间。
【问题讨论】:
-
添加一个shebang,然后将您的脚本粘贴到那里:shellcheck.net
-
谢谢你的链接,它真的很有帮助。
标签: bash validation for-loop scripting