3

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?

2 Answers 2

3

In general, I try to avoid provoking errors from SQL queries. Rather, I aim to work with the results they return and make sense of them.

That said, you could (quite hacky approach!) provoke a division by zero:

SELECT (1 / (SELECT count(*) FROM pg_tables WHERE tablename='$wanted'))::int::boolean;

If a table with the desired name is not existing, the query will fail with ERROR: division by zero. If a table with the desired name is existing, the query will return true.

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

Comments

1

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.

1 Comment

That works. I ended up just doing directly the query I wanted as if it were the right database, and redirecting stderr to /dev/null.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.