0

I have below shell script

#! /bin/sh

for file in $(ls -l scripts/*.sql | awk '{print $NF}'); do 
 psql -h host -d db -U user -p port -f $file;
 result=$?
 if [ $result -ne 0 ] 
   then
   exit 1
 fi
done

$result always comes 0 even if I add some error to sql file. I want to exit shell script if any sql script throws error. Am I missing something in catching the error of last executed statement

5
  • Don't use ls and $() just loop through the globs. Commented Apr 6, 2020 at 8:10
  • try -b Print failed SQL commands to standard error output. This is equivalent to setting the variable ECHO to errors. Commented Apr 6, 2020 at 8:11
  • You don't need to test the exit status as well. Commented Apr 6, 2020 at 8:11
  • You can verify your script via shellcheck.net Commented Apr 6, 2020 at 8:13
  • 1
    @Jetchisel Thanks this link is useful to update script specially around legacy code Commented Apr 6, 2020 at 9:47

1 Answer 1

5

Try: psql -v ON_ERROR_STOP=1 -f $file

This makes psql stopping at first SQL error and returning a non-zero return code in this case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.