Execute command inside kubernetes pod (bash script)

12/3/2018

I am trying to execute a command inside postgres container from shell script. This is what I have so far:

kubectl exec -it <postgres_pod> -n <deployment> -- bash -c "psql -U postgres -d database -c 'select count from table where name='FOO';'"

I am getting the following error:

ERROR: column "foo" does not exist LINE 1: select count from table where name=FOO; ^

The query runs fine inside the container so there must be something wrong with the way I am passing the command. I did try another query:

kubectl exec -it <postgres_pod> -n <deployment> -- bash -c "psql -U postgres -d database -c 'select * from table;'"

This runs fine. So, I am guessing that its someting with the way I am passing the where clause where name='FOO'. How can I get this to work. Kindly help me out.

Update:

Tried escaping using:

1: Double Quotes

kubectl exec -it <postgres_pod> -n <deployment> -- bash -c "psql -U postgres -d database -c 'select count from table where name=\"FOO\";'"

ERROR:  column "FOO" does not exist
LINE 1: select count from table where name="FOO";
                                            ^

2: Single Quotes

kubectl exec -it <postgres_pod> -n <deployment> -- bash -c "psql -U postgres -d database -c 'select count from table where name=\'FOO\';'"

bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
command terminated with exit code 1
-- el323
bash
kubectl
kubernetes

2 Answers

12/3/2018

I have used $ dollar-quoted string in where clause and escaped them using /$.

kubectl exec -it <postgres_pod> -n <deployment> -- bash -c "psql -U postgres -d database -c 'select count from table where name=\$\$FOO\$\$;'"
-- el323
Source: StackOverflow

12/3/2018

That's because the quotes are not properly escaped and then FOO is assumed to be a column name.

Try

kubectl exec -it <pod_id> -n <deployment> -- bash -c "psql -U postgres -d database -c 'select count from table where name=\"FOO\";'"
-- Diego Torres Milano
Source: StackOverflow