Store mysql query output into a shell variable

前端 未结 11 1319
暗喜
暗喜 2020-12-01 06:14

I need a variable to hold results retrieved from the database. So far this is basically what I\'m trying with no success.

myvariable=$(mysql database -u $use         


        
11条回答
  •  情深已故
    2020-12-01 06:38

    You have the pipe the other way around and you need to echo the query, like this:

    myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql db -u $user -p $password)
    

    Another alternative is to use only the mysql client, like this

    myvariable=$(mysql db -u $user -p $password -se "SELECT A, B, C FROM table_a")
    

    (-s is required to avoid the ASCII-art)

    Now, BASH isn't the most appropriate language to handle this type of scenarios, especially handling strings and splitting SQL results and the like. You have to work a lot to get things that would be very, very simple in Perl, Python or PHP.

    For example, how will you get each of A, B and C on their own variable? It's certainly doable, but if you do not understand pipes and echo (very basic shell stuff), it will not be an easy task for you to do, so if at all possible I'd use a better suited language.

提交回复
热议问题