rivenmyst137 rivenmyst137 - 22 days ago 5
Bash Question

Explain this shell output

Why on earth is the output (really, the last line) of:

num=$(redis-cli info | grep instantaneous_ops_per_sec | cut -d : -f 2)
echo num $num
ts=$(date '+%s')
echo ts $ts
ns="$1.ops_per_sec"
echo "$ns"
echo "$ns $num"
echo "$ns $num $ts"


...this:

num 0
ts 1479439922
foo.ops_per_sec
foo.ops_per_sec 0
1479439922_sec 0

Answer

The output of redis-cli ends with a CRLF, but only the LF is stripped by the command substitution. The CR, when output to the terminal, moves the cursor to the beginning of the line. You don't notice that when $num is the last thing output on a line, but in your last case, the space and value of $ts are written on top of the previous data.

The easiest way to fix this is to simply trim any trailing CR from the value of num:

num=${num%$'\r'}