将mysql结果存储在bash数组变量中

时间:2016-02-08 16:35:27

标签: mysql bash

我试图将MySQL结果存储到全局bash数组变量中,但我不知道该怎么做。

我应该将MySQL命令结果保存在一个文件中并在我的for循环中逐行读取文件以进行其他处理吗?

示例:

#Database, table uses

user password
Pierre aaa
Paul bbb

命令:

$results = $( mysql –uroot –ppwd –se  « SELECT * from users );

我希望results包含两行。

4 个答案:

答案 0 :(得分:8)

用于将整个表包含到一个bash变量

中的Mapfile

你可以试试这个:

mapfile result < <(mysql –uroot –ppwd –se  "SELECT * from users;")

echo ${result[0]%$'\t'*}
echo ${result[0]#*$'\t'}

for row in "${result[@]}";do
    echo Name:  ${row%$'\t'*}  pass: ${row#*$'\t'}
done

Nota 这样可以正常工作,而行只有2个字段。更多是可能的,但变得棘手

逐行阅读读表

while IFS=$'\t' read name pass ;do
    echo name:$name pass:$pass
  done  < <(mysql -uroot –ppwd –se  "SELECT * from users;")

读取并循环以将整个表保存为许多变量:

i=0
while IFS=$'\t' read name[i] pass[i++];do
    :;done  < <(mysql -uroot –ppwd –se  "SELECT * from users;")

echo ${name[0]} ${pass[0]}
echo ${name[1]} ${pass[1]}

新的(2018年2月)shell连接器

有一个小工具(在github上)或在我自己的网站上:( shellConnector.sh你可以使用:

一些准备工作:

cd /tmp/
wget -q http://f-hauri.ch/vrac/shell_connector.sh
. shell_connector.sh
newSqlConnector /usr/bin/mysql '–uroot –ppwd'

以下仅适用于演示,请跳至测试快速运行

多数民众赞成。现在,为demo创建临时表:

echo $SQLIN
3

cat >&3 <<eof
CREATE TEMPORARY TABLE users (
  id bigint(20) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(30), date DATE)
eof
myMysql myarray ';'
declare -p myarray
bash: declare: myarray: not found

命令myMysql myarray ';'将发送;然后执行内联命令, 但是由于mysql不会解决任何问题,变量$myarray不会存在。

cat >&3 <<eof
  INSERT INTO users VALUES (1,'alice','2015-06-09 22:15:01'),
       (2,'bob','2016-08-10 04:13:21'),(3,'charlie','2017-10-21 16:12:11')
eof
myMysql myarray ';'
declare -p myarray
bash: declare: myarray: not found

运行测试:

好的,那么现在:

myMysql myarray "SELECT * from users;"
printf "%s\n" "${myarray[@]}"
1   alice   2015-06-09
2   bob     2016-08-10
3   charlie 2017-10-21

declare -p myarray
declare -a myarray=([0]=$'1\talice\t2015-06-09' [1]=$'2\tbob\t2016-08-10' [2]=$'3\tcharlie\t2017-10-21')

此工具处于构建的早期阶段...您必须在重新使用之前手动清除变量:

unset myarray
myMysql myarray "SELECT name from users where id=2;"
echo $myarray
bob

declare -p myarray
declare -a myarray=([0]="bob")

答案 1 :(得分:0)

  1. 如果您希望在脚本中获取全局变量,只需为varname指定一个值:

    export VARNAME=('var' 'name')
    echo ${VARNAME[0]} # will echo 'var'
    

    执行此操作后,您可以在初始化后在脚本中的任意位置访问VARNAME的值。

  2. 如果您希望在多个脚本之间共享变量,则必须使用export:

    script1.sh:

    echo ${VARNAME[1]} # will echo 'name', provided that 
                       # script1.sh was executed prior to this one
    

    script2.sh

    <action name="eliminarJug" class="tdp.proyectoWeb.ManejadorJugadorAction" method="executeEliminarJugador" > 
        <interceptor-ref name="storeStack" />       
        <result name="success" type="redirectAction">
            <param name="actionName">verInformacionPartidoAdmin</param>
            <param name="IdPartido">${IdPartido}</param>
        </result>
        <result name="error" type="redirectAction">
            <param name="actionName">verInformacionPartidoAdmin</param>
            <param name="IdPartido">${IdPartido}</param>            
        </result>                    
    </action>
    
  3. 请注意,导出仅在同一shell实例中运行脚本时才有效。如果你想让它跨越实例工作,你必须将导出变量代码放在.bashrc或.bash_profile中的某个地方

答案 2 :(得分:0)

@F的答案。豪里(Hauri)似乎真的很复杂。

https://stackoverflow.com/a/38052768/470749帮助我意识到我需要使用环绕查询结果的括号()来将其视为数组

#You can ignore this function since you'll do something different.
function showTbl {
    echo $1;
}

MOST_TABLES=$(ssh -vvv -t -i ~/.ssh/myKey ${SERVER_USER_AND_IP} "cd /app/ && docker exec laradock_mysql_1 mysql -u ${DB} -p${REMOTE_PW} -e 'SELECT table_name FROM information_schema.tables WHERE table_schema = \"${DB}\" AND table_name NOT LIKE \"pma_%\" AND table_name NOT IN (\"mail_webhooks\");'")
#Do some string replacement to get rid of the query result header and warning. https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script
warningToIgnore="mysql\: \[Warning\] Using a password on the command line interface can be insecure\."
MOST_TABLES=${MOST_TABLES/$warningToIgnore/""}
headerToIgnore="table_name"
MOST_TABLES=${MOST_TABLES/$headerToIgnore/""}

#HERE WAS THE LINE THAT I NEEDED TO ADD! Convert the string to array:
MOST_TABLES=($MOST_TABLES)
for i in ${MOST_TABLES[@]}; do
    if [[ $i = *[![:space:]]* ]]
    then          
        #Remove whitespace from value https://stackoverflow.com/a/3232433/470749
        i="$(echo -e "${i}" | tr -d '[:space:]')"  
        TBL_ARR+=("$i")
    fi
done
for t in ${TBL_ARR[@]}; do        
    showTbl $t
done

这成功地向我表明${TBL_ARR[@]}具有查询结果中的所有值。

答案 3 :(得分:-1)

results=($( mysql –uroot –ppwd –se "SELECT * from users" ))
if [ "$?" -ne 0 ]
then
  echo fail
  exit
fi