Beto
Beto

Reputation: 28

Simple if then not doing as expected

Using this code:

#!/bin/sh
DBVALUE=$(/opt/mssql-tools/bin/sqlcmd -S server -UUser -P"Password" -dDatabase -Q"SELECT something from table WHERE this = "that" | grep yes)
echo "$DBVALUE"
if [ "$DBVALUE" != "yes" ]
then
  echo "no"
  exit 0
else
  echo "yes"
fi

echo DBVALUE returns "yes" if-then returns "no"

If I swap out my SQL lookup with DBVALUE="yes" the if-then returns "yes"

Why doesn't the DBVALUE result of "yes" from the SQL lookup return a yes in the if-else?

Upvotes: 0

Views: 44

Answers (2)

Beto
Beto

Reputation: 28

I finally figured out the database result was trailing with a bunch of spaces, so "yes " did not equal "yes".

I stripped the spaces: DBV="$(echo "$DBVALUE" | tr -d '[:space:]')"

And it tested successful!

As tripleee pointed out, I can use a flag to remove the spaces: DBVALUE=$(/opt/mssql-tools/bin/sqlcmd -S server -UUser -P"Password" -dDatabase -Q"SELECT something from table WHERE this = 'that'" -W | grep yes)

Upvotes: 0

Palle
Palle

Reputation: 12109

Looks like there is a double quote missing at the end of the sql query. Also, by using unescaped double quotes around "that", the query and everything subsequently in that script might not be executed as expected.

The solution would be to escape the double quotes with a backslash.

DBVALUE=$(/opt/mssql-tools/bin/sqlcmd -S server -UUser -P"Password" -dDatabase -Q"SELECT something from table WHERE this = \"that\"" | grep yes)

Upvotes: 1

Related Questions