0

I'm new to bash scripting and I am practicing with some simple scripts. I am creating a script that connects to a MySQL database, executes a query and echo the results. This is what I have so far but I am being given this frustrating error:

./testsql: line 22: syntax error near unexpected token `queryConfig="mysql -uroot -p1234 test"'
./testsql: line 22: `queryConfig="mysql -uroot -p1234 test"'

This is the function inside my script.

function testFunction{
queryConfig="mysql -uroot -p1234 test"
hello=`$queryConfig"SELECT * FROM test_accounts;"`
echo "Result = " $hello
}

Ok I know that ideally I should not pass the username and password into the script but rather use a config.sh which can then be included in the script. Also it is not ideal to use the root. But here the important thing is that I understand where is the sytax error and why is the interpreter complaining. Once I get this work I can create a config.sh and variables accordingly. Thanks.

2 Answers 2

1

try this

var=$(mysql database -u $user -p$password<<<"SELECT * FROM test_accounts")
Sign up to request clarification or add additional context in comments.

Comments

0

This error:

./testsql: line 22: syntax error near unexpected token `queryConfig="mysql -uroot -p1234 test"'

Says that line 22 of your Bash script has a syntax error (i.e. it isn't valid Bash). The parser doesn't think you can do a variable assignment here. But why?

The issue is in the line above:

function testFunction{

Bash is very whitespace-sensitive, and you're missing a space between your function name and the { character. Try adding a space and you'll resolve this syntax error.


There are other issues in your script (beyond the security concerns you mention) that I'll touch on briefly:

  • Avoid using backticks, prefer $(...) for command substitution. It's easier to read and works better when you start nesting substitutions inside each other.
  • Pay attention to whitespace, e.g. your next line

    hello=`$queryConfig"SELECT * FROM test_accounts;"`
    

    Will execute the command

    mysql -uroot -p1234 testSELECT * FROM test_accounts;
    

    Notice the testSELECT there - you're missing a space.

  • Pay attention to quoting. Quoting in Bash is hard, but it's important to get right. There are some good best-practices to internalize that makes working with quotes in Bash a lot easier.

Comments

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.