I’d want to check whether PostgreSQL is installed on Linux in a script and publish the result. Any ideas on how to go about doing the check?
Asked by Nirmal- thInk beYond
Why don’t you try the which command?
There appears to be no output if you run which psql and Postgres is not installed. The terminal prompt is now ready to take another command:
> which psql >
However, if Postgres is installed, you’ll get a response that includes the path to the Postgres installation:
> which psql /opt/boxen/homebrew/bin/psql
Looking at man, there looks to be another alternative that could assist you:
-s No output, just return 0 if any of the executables are found, or 1 if none are found.
So, as long as your scripting language can execute a terminal command, you should be able to send which -s psql and utilize the return value to see if Postgres is installed. You can then print the result in whatever way you like.
Because I have Postgres installed on my machine, I perform the commands below.
> which -s psql > echo $? 0
this indicates that the command returned 0 and that the Postgres executable was discovered on my PC.
Here’s what you need to know about echo $.
Answered by campo
We can write simply:
output show like:
psql (PostgreSQL) 11.5 (Ubuntu 11.5-1.pgdg18.04+1)
Answered by Chandan Sharma
If it’s based on Debian.
aptitude show postgresql | grep State
But I suppose you could just run it with a flag like —version, which simply prints some information and exits.
“service postgres status” was used to update the information. Try:
service postgres status if [ "$?" -gt "0" ]; then echo "Not installed". else echo "Intalled" fi
Answered by Draco Ater
There is no easy method to accomplish this. All you can do is use a package manager (rpm, dpkg) or look for the files you need in some likely locations. Alternatively, connect to a plausible port (5432) and observe if a PostgreSQL protocol answer is sent. But none of this will be really durable. It’s possible that you might rethink your needs.
Answered by Peter Eisentraut
Because PostgreSQL can be installed and configured in a variety of ways, there is no single simple way to accomplish it.
You can’t count on psql to be on your PATH. You can’t rely on the system having only one psql (multiple versions might be installed in different ways). You can’t do it based on port because there’s no guarantee it’ll be on port 5432 or that numerous versions won’t exist.
Prompt and question the user.
Answered by Craig Ringer
Post is based on https://stackoverflow.com/questions/5803262/how-can-i-check-if-postgresql-is-installed-or-not-via-linux-script