2017-07-07 71 views
1

我遇到了问题,不理解底层原因是什么。MySQL查询在Bash脚本中意外分裂

我有了这三个字段的表:

______________________________________________ 
| cid | order_id | TxRefNum | 
---------------------------------------------- 

我在我的bash脚本制作一个简单的调用(从字面上有没有其他的代码开始)

#!/bin/bash 

mysql --login-path=main-data -e "SELECT 
    cid, 
    order_id, 
    TxRefNum 
FROM database.orders_temp" | 

while read this that other; do 

    echo "$this || $that || $other" 
done 

我预计会看到以下内容:

__________________________________________________________ 
| 29 | F0VIc - CHATEAU ROOFIN | 5555555 | 
---------------------------------------------------------- 

而是我的脚本正在拆分字符串$that分成两个不同的字符串..回声居然是:

___________________________________________________ 
| 29 | F0VIc | - CHATEAU ROOFIN | 
--------------------------------------------------- 

我必须在我的while循环设置我的变量时,设置一个分隔符?我真的很难过!

+0

您的数据可能包含的分隔符。快速测试方法是在您的查询中添加一个替换,您只需用下划线替换空格即可。另外快速建议:避免使用关键字/保留字作为参数/变量:'this'不是参数的最便利的名称。 –

+0

大声笑我明白'这个'(没有双关语意图) - 那些显然不是我的“真正的”变量名称;-) – Zak

回答

1

Getting output from the mysql command formatted in an intelligent way is problematic。在你的情况下,bash正在将解释为分隔符。你需要分裂一种不同的方式。我能够得到这个工作。你会注意到在查询以及在IFS线|在TOPE

#!/bin/bash 

IFS='|' # set the delimiter 
mysql --login-path=main-data -e "SELECT 
    29 as cid, '|', 
    'F0VIc - CHATEAU ROOFIN' as order_id, 
    '|', 
    5555555 as TxRefNum 
FROM dual" | 
while read this that other; do 
    echo "$this || $that || $other" 
done 
+0

很好的解释谢谢! – Zak