Store MySQL query output into a shell variable
Execute your MySQL query result to a bash variable. Replace user, password, dbname, column, table, and condition with your actual parameters. Use echo to confirm the output.
Multiline and multicolumn outputs handling
Multiline outputs
When your MySQL query returns multiple lines, read and iterate:
Above, we're using read within a while loop, buffering each line of the output into an array.
Multicolumn outputs
For multicolumn outputs, handle each column individually:
While looping, read with -r takes care of the multicolumn reading.
Data security
Sensitive data needs to be handled appropriately:
Here, for security, the entered password is hidden with read -sp and removed once used with unset.
Advanced Cases
Selecting Specific Columns
Need to dissect your result, maybe grab a certain column?
Using cut command, you can slice and dice your outputs anyway you want.
Implementing Error Handling
Life's not all rainbows. Errors happen, and they should be handled:
When things get complicated
For complex outputs, other languages like Python or Perl might make your life easier:
Python's mysql.connector allows you to juggle with complex datasets.
Was this article helpful?