-1

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?

user3437721
  • 2,227
  • 4
  • 31
  • 61
  • 2
    Shouldn't it be `RESULT=$(...)`? and not `RESULT='...'`? See: https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash – codeforester Nov 03 '17 at 23:53

1 Answers1

2

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

Menzo Wijmenga
  • 1,011
  • 6
  • 13