1

I am trying to run sql query in if statement. Here is my shell script

#!/bin/bash

var="select col1, col2 from table_name where condition;"

    count=$(ping -c 4 192.168.7.204 | awk -F',' '{ print $2 }' | awk '{ print $1 }')

      if [ $count -eq 0 ]; then

        mysql -h 192.168.7.204 -u username -ppassword db_name<<EOFMYSQL
        $var
        EOFMYSQL

      fi

But it shows me an error

./test.sh: line 18: warning: here-document at line 12 delimited by end-of-file (wanted `EOFMYSQL')
./test.sh: line 19: syntax error: unexpected end of file

1 Answer 1

1

The here-document sentinelEOFMYSQL has to be up against the left margin, not indented:

var="select col1, col2 from table_name where condition;"

count=$(ping -c 4 192.168.7.204 | awk -F',' '{ print $2 }' | awk '{ print $1 }')

if [ $count -eq 0 ]; then    
    mysql -h 192.168.7.204 -u username -ppassword db_name <<EOFMYSQL
$var
EOFMYSQL    
fi

If you change the <<EOFMYSQL to <<-EOFMYSQL you can indent it, as long as you use only tabs and not spaces.

See the manual.

Sign up to request clarification or add additional context in comments.

7 Comments

I am sorry but i don't have much knowledge of it. I am learning sql and shell script too. Can you please explain me in detail?
I mean you can't have any space on the line before EOFMYSQL. It has to be the very first thing on the line.
In this simple case, you don't need a HERE document. Which shell are you using?
@user1934428 I tried without using EOFMYSQL It shows no error but nothing in output. So how do i get to know whether sql query run or not? If run then where is output?
What do you mean by "without using EOFMYSQL"? Post your modified code .... BTW, I asked which shell you are using. It's difficult to discuss the "best" way to solve the problem, without knowing this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.