Bash-在Ubuntu 18中从mysql-client解析中拆分字符串的问题

我有一个脚本,该脚本访问中央数据库服务器(在CentOS 7.7上为mariadb 10.2)以获取随机数据库条目。

#!/bin/bash

function getrandom()
{
     mysql -h 11.22.33.44 -P 3306 -u usr -p password -D dbExample -e "SELECT ip,host FROM hosts ORDER BY RAND() LIMIT 1;"
}

entry=$(getrandom)

数据库具有条目,即:

+----+---------+--------------+
| id | ip      | host         |
+----+---------+--------------+
|  2 | 8.8.8.8 | facebook.com |
|  3 | 1.1.1.1 | google.de    |
+----+---------+--------------+

因此,mysql select应该获得以下字符串:

ip host 8.8.8.8 facebook.com

ip host 1.1.1.1 google.de

所以我下一步要做的是将字符串''分割成一个数组,然后将[2]和[3]写入vars,以进行进一步处理。

在另一台Centos 7.7服务器上,这绝对没有问题:

IFS=' ' read -ra ADDR <<< $entry

甚至

ip="$(cut -d' ' -f3 <<< "$entry")"
host="$(cut -d' ' -f4 <<< "$entry")"

但是,当尝试在ubuntu 18.04上执行脚本时,拆分的所有解决方案似乎都无效。我将mysql-client-core-10.1用于mysql调用。经过一些失败的调试尝试后,我返回到$ entry var的解析。

在这里,我注意到在回显$ entry时,返回了完整的字符串:

echo $entry

returns: ip host 1.1.1.1 google.de

在回显“ $ entry”时,仅返回前两个元素:

echo "$entry"

returns: ip host

我认为,这是问题的根源,但我不明白为什么它在CentOS下有效。

继续执行我的脚本,拆分不起作用。我尝试过:

IFS=' ' read -ra ADDR <<< $entry

保存:$ ADDR中的“ ip主机”

IFS=' ' read -ra ADDR <<< "$entry"

保存:$ ADDR中的“ ip主机”

ip="$(cut -d' ' -f3 <<< "$entry")"
host="$(cut -d' ' -f4 <<< "$entry")"

在两个变量中都保存:“ ip host 8.8.8.8 facebook.com”(是的,这实际上使用了引号,即使这会使“ $(cut -d''-f4

ip="$(cut -d' ' -f3 <<< $entry)"
host="$(cut -d' ' -f4 <<< $entry)"

在两个变量中保存:“ ip主机8.8.8.8 facebook.com”

ip=$(cut -d' ' -f3 <<< $entry)
host=$(cut -d' ' -f4 <<< $entry)

在两个变量中保存:“ ip主机8.8.8.8 facebook.com”

有人可以帮我吗?

编辑:

getrandom | od -t x1的输出:

0000000 69 70 09 68 6f 73 74 0a 38 2e 38 2e 38 2e 38 09
0000020 66 61 63 65 62 6f 6f 6b 2e 63 6f 6d 0a
0000035

谢谢,我想我已经回到正轨:)

i  p  <tab> h  o  s  t <newline> 8  .  8  .  8  .  8 <tab>
f  a  c  e  b  o  o  k  .  c  o  m  <newline>
hell_liul 回答:Bash-在Ubuntu 18中从mysql-client解析中拆分字符串的问题

在mysql客户端的返回值中有选项卡和换行符ascii标志。我通过以下方式删除了它们:

entry=$(echo "${entry//$'\t'/','}")
entry=$(echo "${entry/$'\n'/','}")

此后,hexdump返回:

0000000 69 70 2c 68 6f 73 74 2c 38 2e 38 2e 38 2e 38 2c
0000020 66 61 63 65 62 6f 6f 6b 2e 63 6f 6d 0a
0000035

从那里开始,它与在CentOS上相同:

IFS=',' read -r -a array <<< "$entry"
ip=${array[2]}
host=${array[3]}

Echo在$ ip中返回1.1.1.1,在$ host中返回google.de

谢谢stephanmg,oguz ismail为我指出了正确的方向! =)

当然可以使用sed删除制表符和换行符,这是一种更平滑的方法,但是我无法使其正常工作,所以现在有一个尴尬的解决方案。

本文链接:https://www.f2er.com/3144854.html

大家都在问