PostgreSQL: How to pass parameters from command line?

前端 未结 7 696
孤独总比滥情好
孤独总比滥情好 2020-12-23 15:42

I have a somewhat detailed query in a script that uses ? placeholders. I wanted to test this same query directly from the psql command line (outside the script

7条回答
  •  情话喂你
    2020-12-23 16:29

    I would like to offer another answer inspired by @malcook's comment (using bash).

    This option may work for you if you need to use shell variables within your query when using the -c flag. Specifically, I wanted to get the count of a table, whose name was a shell variable (which you can't pass directly when using -c).

    Assume you have your shell variable

    $TABLE_NAME='users'
    

    Then you can get the results of that by using

    psql -q -A -t -d databasename -c <<< echo "select count(*) from $TABLE_NAME;"
    

    (the -q -A -t is just to print out the resulting number without additional formatting)

    I will note that the echo in the here-string (the <<< operator) may not be necessary, I originally thought the quotes by themselves would be fine, maybe someone can clarify the reason for this.

提交回复
热议问题