How to feed mysql queries from bash

后端 未结 7 1195
小鲜肉
小鲜肉 2020-12-05 17:52

I\'m trying to make a bash script that creates a mysql user and database but I can\'t find a way to feed the sql into mysql, I\'m trying with this format:

my         


        
7条回答
  •  再見小時候
    2020-12-05 17:57

    The reason your attempt did not work was because the < expects a file name and you fed it a string. You would have to do something like

    echo "YOURQUERYSTRINGHERE">tmpfile
    mysql --host=localhost --user=user --password=password dbname 

    ken's suggestion of

     mysql  --host=localhost --user=user --password=password -e "QUERY" dbname
    

    can work, but if you try to use bash variables in your query you can fall foul of parameter expansion. eg

    QUERY="select * from $MYTABLE WHERE name=\"silly@place.com\";"
    mysql --host=localhost --user=user --password=password -e "$QUERY" mydbname
    

    may not do what you expect. One option is use

    echo "$QUERY"|mysql --host=localhost --user=user --password=password mydbname
    

    which works if the query string contains appropriate quoting. Another option is the "here" document as suggested by dogbane.

提交回复
热议问题