I have a bash script that loops through a folder directory for .sql files and executes them. I want to change this so the bash script inserts into a database if the execution is successful and a different function that asks the user a question when executing the MySql results in errors.
I've looked at many solutions so far, but I can't get the executed query's return value into a var to do my conditional checks. I am a rookie in regards to bash scripts, so I am unsure what the correct way to do this is.
Here is the my attempt at the script:
ENV=localdev
exec_migration() {
# $1 - migration folder name
# $2 - name of SQL file to execute
# $3 - environment name
echo "Executing $1 - $2"
# execute the migration.
# If the migration succeeds, update the migrations table
# Else, ask the user if they want to skip the migration if this is the local development environment
mysql -u "${DBUSER}" -p"${DBPASS}" -D "${DBNAME}" < "$2"
status=$? # script doesn't execute this and subsequent lines - see screenshot.
echo "status: $status"
if [ "$status" = "0" ]; then
echo 'yay'
update_migrations_table "$2" "$3"
else
echo 'no'
ask_skip_migration "$2" "$3"
fi
}
for DIR in cms lms; do
echo running migrations on ${DIR}
pushd ../../data/migrations/${DIR}
DBNAME='mylmsdb'
# get the migration files from the cms/lms folder into a set
set +e
SQLS=$(ls -1 *.sql 2>/dev/null)
set -e
# Loop through the set and execute each migration file
for SQL in ${SQLS}; do
exec_migration "${DIR}" "${SQL}" "${ENV}"
done
popd
done
In cms folder, I have 2 test .sql files (a 'good' script that should execute without issues, and a 'bad' one that should always result in a MySQL error):
- My_test_migration_bad.sql
START TRANSACTION;
CREATE TABLE IF NOT EXISTS my_table_bad;
COMMIT;
- My_test_migration_good.sql
START TRANSACTION;
CREATE TABLE IF NOT EXISTS my_table_good(id int AUTO_INCREMENT PRIMARY KEY, goodcolumn int);
COMMIT;
Looking forward to your responses. Thanks in advance!

set -ecauses the rest of the script execution to exit if any command has a nonzero exit status? Why did you choose to enable this if your logic depends on reading the exit status?create tableisn't transactional. Look atmysql --batchmode too. Has advantages in some scenarios processing output.set -e. This script was initially created by someone else, and this is the first modification of this script since they created it years ago. Initial script just executed the SQL without needing to check if it was successful or not.create tablein my test data as its the most common thing this script needs to handle.$statusvariable. Just useif mysql ...; then ...; else ...; di. This avoids the problem withset -e, since it doesn't exit when the command is in a conditional.