diff --git a/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm b/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
index 60bbd5dd445..dce7ccd64d0 100644
--- a/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
+++ b/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
@@ -156,6 +156,13 @@ sub wait_connect
 	# See query() for details about why/how the banner is used.
 	my $banner = "background_psql: ready";
 	my $banner_match = qr/(^|\n)$banner\r?\n/;
+
+	# See comment on similar check in query()
+	if (!defined($ENV{with_readline}) || $ENV{with_readline} ne 'yes')
+	{
+		$banner_match = qr/postgres=# $banner\r?\n/;
+	}
+
 	$self->{stdin} .= "\\echo $banner\n\\warn $banner\n";
 	$self->{run}->pump()
 	  until ($self->{stdout} =~ /$banner_match/
@@ -265,14 +272,22 @@ sub query
 	# to be careful that we don't e.g. match the echoed \echo command, rather
 	# than its output.
 	my $banner = "background_psql: QUERY_SEPARATOR $query_cnt:";
-	my $banner_match = qr/(^|\n)$banner\r?\n/;
+	my $banner_match_stdout = qr/(^|\n)$banner\r?\n/;
+	my $banner_match_stderr = $banner_match_stdout;
+	# If we are built without readline, normal regex doesn't work, since stdout
+	# is read all at once, and the banner is preceeded by "postgres#= ".
+	# stderr still contains only the banner.
+	if (!defined($ENV{with_readline}) || $ENV{with_readline} ne 'yes')
+	{
+		$banner_match_stdout = qr/postgres=# $banner\r?\n/;
+	}
 	$self->{stdin} .= "$query\n;\n\\echo $banner\n\\warn $banner\n";
 	pump_until(
 		$self->{run}, $self->{timeout},
-		\$self->{stdout}, qr/$banner_match/);
+		\$self->{stdout}, qr/$banner_match_stdout/);
 	pump_until(
 		$self->{run}, $self->{timeout},
-		\$self->{stderr}, qr/$banner_match/);
+		\$self->{stderr}, qr/$banner_match_stderr/);
 
 	die "psql query timed out" if $self->{timeout}->is_expired;
 
@@ -286,8 +301,8 @@ sub query
 	# first newline is optional, as there would not be one if consuming an
 	# empty query result.
 	$output = $self->{stdout};
-	$output =~ s/$banner_match//;
-	$self->{stderr} =~ s/$banner_match//;
+	$output =~ s/$banner_match_stdout//;
+	$self->{stderr} =~ s/$banner_match_stdout//;
 
 	# clear out output for the next query
 	$self->{stdout} = '';
