[英]Bash Echo command behaves unexpectedly in a while loop
I am in the process of cleaning up a user database for a client. 我正在为客户端清理用户数据库。 I have the list of users that need to go, and am checking to see if they have any media that they've created before removing them. 我有需要去的用户列表,正在检查是否有他们创建的任何媒体,然后再删除它们。
This is a very simple script, and the problem is relatively minor. 这是一个非常简单的脚本,问题相对较小。 I'm sure it's obvious, I just can't seem to figure it out. 我敢肯定这很明显,我似乎无法弄清楚。
12 while read each;
13 do
14
15 query=$(mysql -u$username -p$password $database -e "select uid,nid,title from node where uid like '$each' limit 1;")
16 if [[ -z $query ]]
17 then query="No nodes"
18 fi
19 if [[ -z $query ]]
20 then query="Error"
21 fi
22 echo -n "$each"
23 echo -n " - "
24 echo "$query"
25 done <$source_file
The problem I'm experiencing is on line 22. I want a single line for each UID in the source file, in the following format: 我遇到的问题在第22行上。我想要源文件中每个UID的一行,格式如下:
UID - Query results
The problem I'm running into is that echoing $each
only works if it is the only argument on the line. 我遇到的问题是,仅当回显$each
是该行上的唯一参数时,它才有效。 In the above example, the result looks like this: 在上面的示例中,结果如下所示:
- Query results
(Forgive the quotes, but the hyphen is interpreted as a bullet on this forum if I don't quote it.) (请原谅引号,但如果我不引号,则连字符在该论坛上被解释为项目符号。)
If I place more than one variable or anything else on the same line as the first echo command, the $each
variable returns empty. 如果在第一个echo命令的同一行上放置多个变量或其他任何变量,则$each
变量将返回空。 It will only display the variable's contents if it is on it's own line, or so it seems. 它只会在单独的行上显示该变量的内容,或者看起来如此。
Further info: 更多信息:
The $each
variable is an integer (as read from the file) $each
变量是一个整数(从文件中读取)
It doesn't matter how I parse it -- IE, if I enter newvar="$each - $query"
and then echo $newvar
the same thing occurs. 我解析它的方式newvar="$each - $query"
,如果我输入newvar="$each - $query"
然后echo $newvar
,则会发生相同的情况。
There is a slightly misleading comment above. 上面有一个稍微令人误解的评论。 echo "$each "
(with a tailing space) overwrites one of the digits of the integer in $each
. echo "$each "
(带有尾部空格)将覆盖$each
整数的一位。
If I place the echo -n "$each"
line earlier in the code (after do
but before the mysql query), the numbers display across the bottom of the output, like a ticker tape. 如果我将echo -n "$each"
行放在代码的前面(在do
之后do
但在mysql查询之前),则数字将显示在输出的底部,如置顶磁带。 This is by far the weirdest part for me, and I can provide a screenshot if that helps. 到目前为止,这对我来说是最奇怪的部分,如果有帮助,我可以提供屏幕截图。
$each
has a CR at the end. $each
的末尾有一个CR。 Strip it before using the variable. 在使用变量之前将其剥离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.