devcloud
devcloud

Reputation: 411

How to format quotes in a PostgreSQL query from a bash script

I am trying to query a kubernetes Postgres pod using a bash script where i want to allow user to enter a variable and then use that variable to query. My bash script is as follows:

#!/bin/bash

echo "give a last name"


read t

kubectl exec -it postgres-pod -- bash -c "psql -U postgres -c 'Select * from users WHERE last_name=\"$t\"'"

I have tried all combinations of single and double quotes but i am unable to pass a string type username. Any suggestions would be appreciated

Upvotes: 3

Views: 1500

Answers (3)

devcloud
devcloud

Reputation: 411

i solved it using @James Brown's answer above:

bash -c "psql -U postgres -c \"Select * from users WHERE last_name='$t';\""

Upvotes: 0

Laurenz Albe
Laurenz Albe

Reputation: 247445

The simple, but bad, solution is

bash -c "psql -U postgres -c \"Select * from users WHERE last_name='$t'\""

This gets the quoting right, but is vulnerable to SQL injection. What if the variable t contains a value with a single quote?

Dealing with that is not so simple; the only way I could think of is using psql variables like this:

echo "Select * from users WHERE last_name = :'var'" | bash -c "psql -U postgres -v var=\"$t\""

Upvotes: 2

Philippe
Philippe

Reputation: 26707

Not sure why you need bash, should this work ?

kubectl exec -it postgres-pod -- psql -U postgres -c "SELECT * FROM users WHERE last_name='$t';"

Upvotes: 0

Related Questions