Home > database >  Need to know if transaction is aborting in script
Need to know if transaction is aborting in script

Time:10-15

I've got a shell script that runs an sql file for my database, problem is that when the transaction is aborted for whatever reason (concurrency issue, etc...) I want to know it has failed so that I can do something else, I'm just not entirely sure how I would read from the command that the transaction has been aborted.

'psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own occurs', I want to check for a non-zero code returned.

For example:

echo 'Deploying SQL'
psql --quiet --single-transaction --file=myfile.sql

The script will be run on a cron so even though it does provide error messages if the transaction is aborted no one will be there to read it everytime, so I need to able to do something when this happens.

For example something like:

local result = psql --quiet --single-transaction --file=myfile.sql

if [[ result == 1 ]]; then
   # do something else
else
   echo 'successful'
fi

I'm relatively new to shell scripting so any help would be greatly appreciated.

CodePudding user response:

You could run the command in an if-else statement.

if psql --quiet --single-transaction --file=myfile.sql; then
    echo 'OK'
else
    echo 'KO'
fi

Or check the previous return status via $? like this:

psql --quiet --single-transaction --file=myfile.sql
local result="$?"
if [[ "$result" == 0 ]]; then
    echo 'OK'
else
    echo 'KO'
fi
  • Related