简体   繁体   中英

connect to mysql db and execute query and export result to variable - bash script

I want to connect to mysql databse and execute some queries and export its result to a varibale, and do all of these need to be done entirely by bash script

I have a snippet code but does not work.

#!/bin/bash

BASEDIR=$(dirname $0)
cd $BASEDIR

mysqlUser=n_userdb
mysqlPass=d2FVR0NA3
mysqlDb=n_datadb

result=$(mysql -u $mysqlUser -p$mysqlPass -D $mysqlDb -e "select * from confs limit 1")

echo "${result}" >> a.txt

whats the problem ?

The issue was resolved in the chat by using the correct password.

If you further want to get only the data , use mysql with -NB (or --skip-column-names and --batch ).

Also, the script needs to quote the variable expansions, or there will be issues with usernames/passwords containing characters that are special to the shell. Additionally, uppercase variable names are usually reserved for system variables.

#!/bin/sh

basedir=$(dirname "$0")

mysqlUser='n_userdb'
mysqlPass='d2FVR0NA3'
mysqlDb='n_datadb'

cd "$basedir" &&
mysql -NB -u "$mysqlUser" -p"$mysqlPass" -D "$mysqlDb" \
      -e 'select * from confs limit 1' >a.txt 2>a-err.txt

Ideally though, you'd use a my.cnf file to configure the username and password.

See eg

Do this:

result=$(mysql -u $mysqlUser -p$mysqlPass -D $mysqlDb -e "select * from confs limit 1" | grep '^\|' | tail -1)

The $() statement of Bash has trouble handling variables which contain multiple lines so the above hack greps only the interesting part: the data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM