PostgreSQL - query from bash script as database user 'postgres'

后端 未结 8 1075
[愿得一人]
[愿得一人] 2020-12-22 19:22

I have a table in my PostgreSQL database which has 3 columns - c_uid, c_defaults and c_settings. c_uid simply stores the

相关标签:
8条回答
  • 2020-12-22 19:57

    In my case the best solution including the requirement for authentication is:

    username="admin"
    new_password="helloworld"
    
    PGPASSWORD=DB_PASSWORD \
      psql -h HOSTNAME -U DB_USERNAME -d DATABASE_NAME -c \
      "UPDATE user SET password = '$new_password' WHERE username = '$username'"
    

    This command will update a password of a user e.g. for recovery case.

    Info: The trade-off here is that you need to keep in mind that the password will be visible in the bash history. For more information see here.

    Update: I'm running the databse in a docker container and there I just need the commmand: docker exec -i container_name psql -U postgres -d postgres -c "$SQL_COMMAND"

    0 讨论(0)
  • Try this one:

    #!/bin/bash
    psql -U postgres -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"
    

    Or using su:

    #!/bin/bash
    su -c "psql -d database_name -c \"SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'\"" postgres
    

    And also sudo:

    #!/bin/bash
    sudo -u postgres -H -- psql -d database_name -c "SELECT c_defaults  FROM user_info WHERE c_uid = 'testuser'"
    
    0 讨论(0)
提交回复
热议问题