avasin avasin - 1 year ago 56
Bash Question

Why bash script breaks if it meets space in this example?

I need to execute following command on multiple servers:

mysql -h -uroot -psecret mydatabase -e 'SELECT 1;'

So, i have
script, which echo-es dynamic string:

echo -n "mysql -h -uroot -psecret mydatabase -e 'SELECT 1'"

script, who executes the given string:


If i execute `./test2.sh, i will see help output, command will be not executed.

If i remove spaces in mysql query
or the whole
param, and then execute
script, everything works.

Why this is happening? Can you please describe this magic?

My bash version is 4.2.46.

Answer Source

As long as you control and trust command line coming from test1.sh, you can use dreaded eval in test2.sh like this:

eval "$cmd"

Why and when should eval use be avoided in shell scripts?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download