avasin avasin - 3 days ago 4
Bash Question

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

I need to execute following command on multiple servers:

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


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

#!/bin/bash
echo -n "mysql -h 127.0.0.1 -uroot -psecret mydatabase -e 'SELECT 1'"


And
test2.sh
script, who executes the given string:

#!/bin/bash
CMD=`./test1.sh`
$CMD


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

If i remove spaces in mysql query
SELECT 1
or the whole
-e
param, and then execute
./test2.sh
script, everything works.

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

My bash version is 4.2.46.

Answer

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

#!/bin/bash
cmd="$(./test1.sh)"
eval "$cmd"

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

Comments