sqlcmd in bash file - store to variable

为君一笑 提交于 2020-08-26 12:52:58

问题


Running in a docker container, I am trying to determine if a table exits in the mssql database:

RESULT='/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -d master -i "SELECT name FROM master.sys.databases WHERE name = N'MyTable'"'
    if [ "$RESULT" == "MyTable" ]; then
        echo YES
    fi
    echo "$RESULT"

echo "$RESULT" always just outputs the entire command as a string, its not getting executed. So its just assigning it as a sting...

How can I execute it and assign the result?


回答1:


Bash does not execute commands defined in single quotes. Single quotes are used for string definitions.

What you try to do is called command substitution. And it can be done in two different ways:

RESULT=`command` 
RESULT=$(command)

So your example should look like this:

RESULT=`/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -d master -i "SELECT name FROM master.sys.databases WHERE name = 'MyTable'`
if [ "$RESULT" == "MyTable" ]; then
    echo YES
fi
echo "$RESULT"

You can find more information regarding command substitution here: https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html



来源:https://stackoverflow.com/questions/47105736/sqlcmd-in-bash-file-store-to-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!