开发者

Bash Script - If statement within quoted command

开发者 https://www.devze.com 2023-03-05 22:33 出处:网络
Within a bash script 开发者_如何学JAVAI am running a sql query via \'psql -c \'. Based off of the arguements given to the bash script, the where claus of the select command will be different. So basic

Within a bash script 开发者_如何学JAVAI am running a sql query via 'psql -c '. Based off of the arguements given to the bash script, the where claus of the select command will be different. 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. 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. Doh!


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. If $VAR is empty, nothing will be substituted.


Save ascript, e.g. 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"


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消