我有一个从MySQL读取数据的脚本(下面的get_sql_results函数),然后读取每行,用awkparsing单个列。
除了将通过ssh的mysql查询结果分配给cmusername的行之外,一切正常。 当包含这一行时,只有$结果的第一行被读取,并且在完成第一次迭代之后,该脚本似乎在读取循环中“转义”。
当我注释掉cmusername =行时,它会像我所期望的那样显示多行。
这是主要的脚本:
new_results() { get_sql_results printf %s "$results" | while read -r line do accounttyperaw=$(echo -en "$line" | awk -F $'\t' '{print $5}') accountstatusraw=$(echo -en "$line" | awk -F $'\t' '{print $3}') accountname=$(echo -en "$line" | awk -F $'\t' '{print $4}') datelastchange=$(echo -en "$line" | awk -F $'\t' '{print $8}') cmuserid=$(echo -en "$line" | awk -F $'\t' '{print $9}') accounttype=$( get_account_type $accounttyperaw ) accountstatus=$( get_account_status $accountstatusraw ) cmusername=$(ssh -p $mysqlport username@remotemysqlserver "/usr/local/mysql/bin/mysql -hdb00 -udba -ppassword -N -e \"SELECT username from userapp.users where userapp.users.user_id rlike '$cmuserid'; \" ") echo -en "$domainname\t" echo -en "$accounttype\t" echo -en "$accountstatus\t" echo -en "$accountname\t" echo -en "$datelastchange\t" echo -en "$cmusername\t" echo done } new_results
编辑 – 解决:
ssh需要-n传递给它。 请参阅下面的答案。
需要包含-n在ssh命令中
https://stackoverflow.com/questions/346445/bash-while-read-loop-breaking-early
-n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)
如果你的Bash版本支持这些特性,另一种使用ssh工作的方法是使用进程replace和备用文件描述符。
while read -r -u 3 line do ... cmusername=$(ssh -p $mysqlport username@remotemysqlserver "/usr/local/mysql/bin/mysql -hdb00 -udba -ppassword -N -e \"SELECT username from userapp.users where userapp.users.user_id rlike '$cmuserid'; \" ") ... done 3< <(printf %s "$results")
这具有在while循环中不创build子shell的额外优点,因此在循环结束后,循环中设置的variables是可用的。 即使您没有使用备用文件描述符,也可以使用此function。
你看不出有什么closures的parenthezis。 这可能是问题吗?
cmusername=$(ssh -p $mysqlport username@remotemysqlserver "/usr/local/mysql/bin/mysql -hdb00 -udba -ppassword -N -e \"SELECT username from userapp.users where userapp.users.user_id rlike '$cmuserid'; \" "
应该是的
cmusername=$(ssh -p $mysqlport username@remotemysqlserver "/usr/local/mysql/bin/mysql -hdb00 -udba -ppassword -N -e \"SELECT username from userapp.users where userapp.users.user_id rlike '$cmuserid'; \" ")