简体   繁体   中英

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:

UID - Query results

The problem I'm running into is that echoing $each only works if it is the only argument on the line. 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. It will only display the variable's contents if it is on it's own line, or so it seems.

Further info:

  1. The $each variable is an integer (as read from the file)

  2. It doesn't matter how I parse it -- IE, if I enter newvar="$each - $query" and then echo $newvar the same thing occurs.

  3. There is a slightly misleading comment above. echo "$each " (with a tailing space) overwrites one of the digits of the integer in $each .

  4. 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. 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. Strip it before using the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM