rivenmyst137 rivenmyst137 - 1 year ago 115
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

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download