rivenmyst137 rivenmyst137 - 18 days ago 5
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

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.

Comments