我有一个脚本,该脚本访问中央数据库服务器(在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>