Search code examples
mysqlbashbackticks

Bash for loop: Backticks


I have this code

$db=test-1
for T in `mysql -u$dbUser -p$dbPass -N -B -e 'show tables from '$db`;
do
count=$((count+1))
mysqldump --skip-comments --compact --skip-lock-tables -u$dbUser -p$dbPass $db $T > $GIT_MYSQL/$T.sql
done
done;

It gives me this error

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1' at line 1

How can I resolve it?


Solution

  • You're not declaring your database name variable properly. Try doing this:

    $db=test-1
    echo "My database is called $db"
    

    Compare the output with this:

    db=test-1
    echo "My database is called $db"
    

    Taking into account comments above and proper (I hope) quoting, your script like this should work:

    dbUser="user"
    dbPass="pass"
    db="test-1"
    for T in $(mysql -u "$dbUser" -p"$dbPass" -N -B -e "show tables from $db")
    do
        mysqldump --skip-comments --compact --skip-lock-tables -u "$dbUser" -p"$dbPass" "$db" "$T" > "$GIT_MYSQL/$T.sql"
    done