在kubernetes pod中执行命令(bash脚本)

时间:2018-12-03 06:53:56

标签: bash kubernetes kubectl

我正在尝试从shell脚本在postgres容器内执行命令。这是我到目前为止的内容:

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; ^

查询在容器内运行良好,因此我传递命令的方式一定存在问题。我确实尝试了另一个查询:

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

运行正常。因此,我猜想它与我传递where子句where name='FOO'的方式有关。我怎样才能使它工作。请帮我。

更新

尝试使用以下方法进行转义:

1:双引号

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:单引号

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

3 个答案:

答案 0 :(得分:2)

我在where子句中使用了$$ dollar-quoted string ,并使用/$对其进行了转义。

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

答案 1 :(得分:1)

那是因为引号没有正确转义,然后FOO被认为是列名。

尝试

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

答案 2 :(得分:1)

看起来像查询条件元素,name='value' 应该在单引号内。

试试这个:它有效!

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