通过MySQL的Bash脚本循环 [英] Bash Script Loop Through MySQL

查看:42
本文介绍了通过MySQL的Bash脚本循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个bash脚本,该脚本可以从远程数据库中检索MySQL数据.实际上我已经完成了,但是现在我需要做的是以某种方式遍历记录并将变量传递给另一个bash文件.这是我的MySQL呼叫:

I need a bash script that can retrieve MySQL data from a remote data base. Actually I have that done, but what I need it to do now is loop through the records somehow and pass a variable to another bash file. Here's my MySQL call:

mysql -X -u $MyUSER -p$MyPASS -h$MyHOST -D$MyDB -e'SELECT `theme_name`, `guid` FROM `themes` WHERE `theme_purchased`="1" AND `theme_compiled`='0';' > themes.xml
download_themes.sh

它现在将数据导出到一个名为theme.xml的xml文件中,我只是想找出某种方法来遍历数据.我试图避免PHP和Perl,而只是尝试使用bash.预先感谢.

It exports the data into an xml file called theme.xml right now, I was just trying to figure out some way to loop through the data. I am trying to avoid PHP and perl and just trying to use bash. Thanks in advance.

推荐答案

类似:

mysql -e "SELECT `theme_name`, `guid` FROM `themes` WHERE `theme_purchased`='1' AND `theme_compiled`='0'" | while read theme_name guid; do
    # use $theme_name and $guid variables
    echo "theme: $theme_name, guid: $guid"
done

简而言之

:当输出是管道时, mysql 命令输出以'\ n'分隔的记录和以'\ t'分隔的字段. read 命令读取一行,分成多个字段,然后将每个字段放在一个变量上.

in short: the mysql command outputs record separated by '\n' and fields separated by '\t' when the output is a pipe. the read command reads a line, splits in fields, and puts each on a variable.

如果您的数据在字段中有空格,则默认的 read 拆分会出现一些问题.有一些解决方法;但是,如果您仅读取两个字段,并且其中一个字段不应有任何空格(例如 guid ),则可以将"dangerous"字段放在最后,然后将 read会将所有多余"都放在最后一个变量中.

if your data has spaces in the fields, you get some problems with the default read splitting. there are some ways around it; but if you're only reading two fields and one of them shouldn't have any spaces (like the guid), then you can put the 'dangerous' field at the end, and read will put everything 'extra' in the last variable.

像这样:

mysql -e "SELECT `guid` `theme_name`, FROM `themes` WHERE `theme_purchased`='1' AND `theme_compiled`='0'" | while read guid theme_name; do
    # use $theme_name and $guid variables
    echo "theme: $theme_name, guid: $guid"
done

这篇关于通过MySQL的Bash脚本循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆