我已经完成了使用顺序脚本目录升级
MySQL 5.7 DB并将它们与DB中的版本字段进行比较的任务.
您应查询数据库,然后将返回的表编号与目录中的脚本进行比较,如果编号低于最高编写的脚本,则执行所有导致最高编写的脚本.脚本的编号也可能存在差距
但是我已经创建了一个问题的解决方案 – 除了我无法让脚本按顺序执行.如果编号中存在间隙,我的grep会拉出另一个共享相同编号的脚本 – 我怎么能避免这种情况?
即grep为6但它执行66.update.sql而不是6.update.sql
注意;我也知道if语句$CURRENT_DB_VERSION -lt 9可能是多余的 – 但是我尝试解决任何脚本都有一个前面带有0的单个整数的问题.
我确实创建了一个脚本版本,我只使用sort -n | head -1函数按顺序执行脚本并在执行后删除它们 – 但是我无法让脚本在数据库版本上开始执行.sql脚本.
#!/bin/bash ####### Usage check [[ $# -ne 5 ]] && echo -e "Please provide the sql scripts directory,username,hostname,database and password \nUSAGE: ./sql_upgrade.sh /directory username hostname dbname password" && exit ####### access / store db information cd $1 user=$2 host=$3 database=$4 pass=$5 ######## DB Version store MysqL -u $user -h $host -p$pass -D $database -e "SELECT version FROM versionTable" > dbvers.out CURRENT_DB_VERSION=`cat dbvers.out | grep -o '[0-9]\+'` highest_upgrade_version=`ls $(pwd) | grep -Eo '[0-9]+' | sort -rn | head -n 1 | awk 'NR' | sed 's/^0*//'` ######### create list of scripts and order them ls $(pwd) | grep .sql | sort -n >> scripts_list.txt while [[ $CURRENT_DB_VERSION -lt $highest_upgrade_version || $CURRENT_DB_VERSION -eq $highest_upgrade_version ]] do next_script_to_execute=`grep -Eo $CURRENT_DB_VERSION scripts_list.txt | sort -n | head -n 1` if [[ $next_script_to_execute -gt $CURRENT_DB_VERSION || -z $next_script_to_execute ]] then ((CURRENT_DB_VERSION++)) elif [[ $CURRENT_DB_VERSION -lt 9 ]] then for i in $(ls $(pwd) | sort -n| grep -E "^[0]" | grep $CURRENT_DB_VERSION| head -1); do MysqL -u $user -h $host -p$pass -D $database < $i echo $i "is currently being executed" ((CURRENT_DB_VERSION++)) done else for i in $(ls $(pwd) | sed 's/^[1-9]*\+ //' | grep -E $CURRENT_DB_VERSION | sort -n | head -n 1); do MysqL -u $user -h $host -p$pass -D $database < $i ((CURRENT_DB_VERSION++)) echo $i "is currently being executed" done fi done ((CURRENT_DB_VERSION--)) echo "Current version of the Database is: "$CURRENT_DB_VERSION MysqL -u $user -h $host -p$pass -D $database -e "UPDATE versionTable SET version = $CURRENT_DB_VERSION" ### cleanup temp files rm -rf scripts_list.txt rm -rf dbvers.out
解决方法
我觉得你过于复杂了.
这里的最小示例是您需要的逻辑:
CURRENT_DB_VERSION=5 for FILE in `ls -1 |sort -n` do FILEVERSION=$(echo $FILE | sed -e 's:^0*::' | sed -e 's/[^0-9]*//g') echo "Filename: $FILE Version: $FILEVERSION" if (( $FILEVERSION > $CURRENT_DB_VERSION )); then echo "File $FILEVERSION is newer version than database $CURRENT_DB_VERSION" # execute the file here else echo "File $FILEVERSION is older or same version as database version $CURRENT_DB_VERSION" fi done