show data_directory

result (example from Windows): “C:/Program Files/PostgreSQL/9.4/data”

Can be used in Linux bash script this way:

datadir=$(psql -U postgres -t -c "show data_directory")

But sometimes things are not so easy – if you do not have superuser user for PostgreSQL. Then you can try this small script:



# try to find pg data directory with query - does not work for nosuperusers
pgdatadir=$(psql -U ...your_pg_user... -d postgres -t -c "select setting from pg_settings where name = 'data_directory'" 2>/dev/null)

# if query did not find value let's try process list
if [ "$pgdatadir" == "" ]; then
	# first we try to find "-D" part of postgres process
	pgdatadir=$(ps -eo cmd|grep ${pgprocess}|grep -v grep|awk '{split($0,array," -D ")} END{print array[2]}'|cut -d' ' -f1)

if [ "$pgdatadir" == "" ]; then
	# if still nothing let's try config file
	pgconfig=$(ps -eo cmd|grep ${pgprocess}|grep -v grep|awk '{split($0,array,"config_file=")} END{print array[2]}'|xargs)
	if [ "$pgconfig" != "" ]; then
		pgdatadir=$(sudo cat ${pgconfig}|grep data_directory|cut -d'#' -f1|cut -d'=' -f2|tr -s ' '|xargs)

if [ "$pgdatadir" == "" ]; then
	echo "ERROR: cannot find pg data directory"
	exit 1