Search code examples
sqlpostgresqlpsql

psql: how to exit with error if query returns 'False'?


I'm using psql to check if a table exists in a given database. The command below works fine to return t for True or f for False:

psql -U $user -d $db -t -c "SELECT EXISTS (
    SELECT FROM pg_tables WHERE tablename='$wanted');"

When the table doesn't exist, I get 'f'.

Instead, I would like psql to exit with a non-zero exit status if the query returned False.

Is that possible?


Solution

  • Try this:

    psql -U $user -d $db -t -c "select * from '$wanted' limit 1"
    echo $?
    

    If the table does not exist the exit code is 1.