gpt4 book ai didi

shell - 如何从 shell 脚本执行 sql 查询

转载 作者:行者123 更新时间:2023-12-04 05:46:12 39 4
gpt4 key购买 nike

我正在编写一个 shell 脚本来在 postgres 中运行一堆查询。

这是我写的剧本。

#!/bin/sh
host="172.16.7.102"
username="priyank"
dbname="truaxis"
x=1
echo "Connection done"
while [ $x -le 3 ]
do
x=$(($x + 1 ))
echo "Connection $x"
psql -h $host $dbname $username << EOF
select * from students where sid = $x;
EOF
done

这个脚本有两个问题。
  • pgtest1.sh: 17: 语法错误:意外的文件结尾(期望“完成”)
  • 如何在 sql 中动态传递 $x

  • 我想每次迭代创建新的数据库连接。

    我是 postgre 和 shell 的新手。

    谢谢

    普里扬克

    最佳答案

    1) pgtest1.sh: 17: Syntax error: end of file unexpected (expecting "done")



    您需要单独在自己的行中使用 EOF(没有空格等)
         psql -h $host $dbname $username << EOF
    select * from students where sid = $x;
    EOF

    2) how do I pass $x in the sql dynamically


    $ sh scriptname.sh value_of_x

    然后在你的脚本中
    x=$1

    关于shell - 如何从 shell 脚本执行 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10649794/

    39 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com