我在 ubuntu 中创建了一个简单的 bash 脚本来备份我的项目:
#!/bin/bash
save_backup_path=~/Downloads/my_backup
web_projects_path=~/Downloads/my_backup/projects
cd $web_projects_path || return
for f in *; do
if [ -d "$f" ]; then
echo "backup project $f";
tar -zcf $save_backup_path/"$f"-$(date +%d-%m-%Y).tar.gz --exclude="$f"/node_modules --exclude="$f"/vendor --exclude="$f"/storage/framework/views/*.php --exclude="$f"/public/uploaded "$f"
fi
done
它将为每个文件夹(项目名称)创建一个 tar.gz。
我想要创建一个菜单并选择我想要创建备份的项目例如:(1、2、3......或*代表全部)
我不知道如何处理选择并完成工作
我用它来存储所有项目名称(文件夹名称)
for f in *; do
if [ -d "$f" ]; then
readarray -t project_names < <(echo "$f")
fi
done
但在列出选择时
echo "Select project for backup:"
select choice in "${project_names[@]}"; do
[[ -n $choice ]] || { echo "Invalid choice. Please try again." >&2; continue; }
break
done
它只显示最后一个(最后一个文件夹名称)。
我怎样才能列出所有项目并为选定的一个或全部创建 tar.gz(如果选定的是 *)
***更新****
#!/bin/bash
### backup the projects
save_backup_path=~/Downloads/my_backup
web_projects_path=~/Downloads/my_backup/projects
cd $web_projects_path || return
declare -a project_names
i=1
for d in */
do
project_names[i++]="${d%/}"
done
echo "Select project for backup:"
select choice in "${project_names[@]}"; do
[[ -n $choice ]] || { echo "Invalid choice. Please try again." >&2; continue; }
break
done
echo "backup project $choice ..."
tar -zcf $save_backup_path/"$choice"-$(date +%d-%m-%Y).tar.gz --exclude="$choice"/node_modules --exclude="$choice"/vendor --exclude="$choice"/storage/framework/views/*.php --exclude="$choice"/public/uploaded "$choice"
我已经创建了带选项的选定,现在它仅适用于选定的项目。我该如何处理所有项目?如果用户选择 * 以将它们全部(单独)
答案1
我知道如何备份所有项目。将 * 添加到现有数组
最终版本如下:
#!/bin/bash
save_backup_path=~/Downloads/my_backup
web_projects_path=~/Downloads/my_backup/projects
cd $web_projects_path || return
declare -a project_names
i=1
for d in */
do
project_names[i++]="${d%/}"
done
project_names[i++]="*"
echo "Select project for backup:"
select choice in "${project_names[@]}"; do
[[ -n $choice ]] || { echo "Invalid choice. Please try again." >&2; continue; }
break
done
backup_project() {
echo "backup project $1 ..."
tar -zcf $save_backup_path/"$1"-$(date +%d-%m-%Y).tar.gz --exclude="$1"/node_modules --exclude="$1"/vendor --exclude="$1"/storage/framework/views/*.php --exclude="$1"/public/uploaded "$1"
}
if [ "$choice" == "*" ]; then
unset project_names[-1]
for project in "${project_names[@]}"; do
backup_project "$project"
done
else
backup_project "$choice"
fi