3

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

6
  • Is there an error message? If so, add it to your question (no comment). Commented Oct 26, 2020 at 18:41
  • This might help: How to debug a bash script? Commented Oct 26, 2020 at 18:42
  • 1
    @JamesBrown Sorry for the typo I either get a "column last_name doesn't exist" or "There is a syntax error at the end of line" Commented Oct 26, 2020 at 19:03
  • 1
    bash -c "psql -U postgres -c \"Select * from users WHERE last_name='$t';\"" Commented Oct 26, 2020 at 19:06
  • 1
    @JamesBrown It works!! thanks a lot Commented Oct 26, 2020 at 19:08

3 Answers 3

2

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\""
Sign up to request clarification or add additional context in comments.

Comments

0

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';"

1 Comment

Thanks for the answer but i already tried this and it didn't work
0

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

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

Comments

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.