rivenmyst137 rivenmyst137 - 1 year ago 100
Bash Question

parsing at command line works but fails in shell script

Why would this work at the command line:

redis-cli info | grep instantaneous_ops_per_sec | cut -d : -f 2

...but not work when I assign that to a variable inside a shell script? e.g.,

num=`redis-cli info` | grep instantaneous_ops_per_sec | cut -d : -f 2

Relatedly, why does assigning the raw output of
redis-cli info
to a shell variable and then echoing it result in a garbled version of the redis-cli output?

Answer Source

When capturing to a variable you should put the entire chain of commands in a subshell, not just the beginning portion:

num=$( redis-cli info | grep instantaneous_ops_per_sec | cut -d : -f 2 )

Also it's better to use $( ) rather than legacy backticks.

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