rivenmyst137 rivenmyst137 - 3 months ago 29
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
echo "$ns"
echo "$ns $num"
echo "$ns $num $ts"


num 0
ts 1479439922
foo.ops_per_sec 0
1479439922_sec 0


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: