简体   繁体   English

Bash脚本-带引号的命令中的If语句

[英]Bash Script - If statement within quoted command

Within a bash script I am running a sql query via 'psql -c '. 在bash脚本中,我通过'psql -c'运行一个sql查询。 Based off of the arguements given to the bash script, the where claus of the select command will be different. 根据对bash脚本的争论,select命令的子句将有所不同。 So basically I need to know if its possible to do something like this: 所以基本上我需要知道是否有可能做这样的事情:

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

and so on for as many arguments. 以此类推。 I know I could do this much easier in a sql function if I just passed the arguments but that really isnt an option. 我知道,如果我只是传递参数,则可以在sql函数中更轻松地完成此操作,但这实际上不是一个选择。 Thanks! 谢谢!

Edit: 5 seconds after posting this I realize I could just create a string before calling the psql command and then call the psql command on that. 编辑:发布此消息后5秒钟,我意识到我可以在调用psql命令之前先创建一个字符串,然后在其上调用psql命令。 Doh! 卫生署!

Save ascript, eg query.sh: 保存脚本,例如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"

Call it like 像这样称呼它

chmod +x ./query.sh
./query.sh "id in (1,2,3)" "modified_by='myname'"
SQL="select x,y,z FROM foobar"
if [ "$1" != "" ]
then
   SQL="$SQL where $1"
fi
psql "$SQL"
psql -c "SELECT columns FROM table ${1:+WHERE $1} ${2:+WHERE $2}"

This uses the "use alternate value" substitution - ${VAR:+alternate} - where alternate is substituted if $VAR is set and not empty. 它使用“使用备用值”替换- ${VAR:+alternate} -如果设置了$VAR且不为空,则alternate为“替换”。 If $VAR is empty, nothing will be substituted. 如果$VAR为空,则不会替换任何内容。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM