Bash脚本 - 如果引用命令中的语句

时间:2011-05-13 12:51:02

标签: sql linux bash select

在bash脚本中,我通过'psql -c'运行sql查询。根据给予bash脚本的论据,select命令的where claus将有所不同。所以基本上我需要知道是否可以做这样的事情:

psql -c "select statement here until we get to the where clause at which point we break out of statement and do"
if (arg1 was given)
    concatenate "where arg1" to the end of the above select statement
if (arg2 was given)
    concatenate "where arg2" to the end of the above select statement
对于尽可能多的论点,

等等。我知道如果我只是传递了参数,我可以在sql函数中更容易地做到这一点,但这真的不是一个选项。谢谢!

编辑:发布后5秒我意识到我可以在调用psql命令之前创建一个字符串,然后在其上调用psql命令。卫生署!

4 个答案:

答案 0 :(得分:2)

保存ascript,例如query.sh:

#!/bin/bash

query="select statement here until we get to the where clause at which point we break out of statement and do"

if [ $# -gt 0 ]
then
    query+=" where $1"
    shift
fi

while [ $# -gt 0 ]
then
    query+=" and $1"
    shift
fi

psql -c "$query"

称之为

chmod +x ./query.sh
./query.sh "id in (1,2,3)" "modified_by='myname'"

答案 1 :(得分:1)

SQL="select x,y,z FROM foobar"
if [ "$1" != "" ]
then
   SQL="$SQL where $1"
fi
psql "$SQL"

答案 2 :(得分:1)

psql -c "SELECT columns FROM table ${1:+WHERE $1} ${2:+WHERE $2}"

这使用“使用替代值”替换 - ${VAR:+alternate} - 如果alternate设置为非$VAR,则替换为$VAR。如果{{1}}为空,则不会替换任何内容。

答案 3 :(得分:0)

stmt="select statement here until we get to the where clause at which point we break out of statement and do"

if (( $# > 0 ))
then
    stmt="$stmt where $1"
fi
if (( $# > 1 ))
then
    stmt="$stmt where $2"
fi

psql -c "$stmt"