7

I'm having trouble figuring out a basic division command.

count = redis-cli llen domains; echo $count returns 1000

How can I echo $count/1000?

I've tried different combinations of:

echo `expr $count / 1000`;
echo $count/1000;
echo ($count / 1000);

Could someone help me craft this command and explain how it should be setup?

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
d-_-b
  • 1,167
  • 5
  • 18
  • 27
  • The first one should have worked.  But (a) You should always quote your shell variable references (e.g., `"$count"`) unless you have a good reason not to, and you’re sure you know what you’re doing.  (b) `echo $(expr "$count" / 1000)` is preferred over `echo \`expr "$count" / 1000\``, and (3) Just plain `expr "$count" / 1000` would have been good enough. Jason’s answer is better; I’m just saying that what you had should have worked.  Also note (d) shell arithmetic is integer-only: 1999/1000 would evaluate to 1. – G-Man Says 'Reinstate Monica' Oct 15 '16 at 04:16

1 Answers1

14

You were getting closer...

See the Wooledge Wiki on arithmetic expression. In your example, you would use:

echo $(( count / 1000 ))

Note that you don't require the $ before the variable inside (( )) as the $ outside performs the substitution. (( )) without the leading $ is a Bash-only feature. $(( )) substitution is allowed in the POSIX shell.

jasonwryan
  • 71,734
  • 34
  • 193
  • 226
  • The inside `$` is needed in some sh implementations (in particular some older versions of BSDs sh based on the Almquist shell like dash) as the POSIX specification used to be unclear on that front. `((...))` is not bash-only. It comes from ksh and is also supported by zsh. You need quotes around `$((...))` as it's subject to word splitting. – Stéphane Chazelas Dec 03 '13 at 06:46
  • @StephaneChazelas You should just edit that in... – jasonwryan Dec 03 '13 at 06:49
  • I'm trying, but the Wooledge site seems to be unresponsive. – Stéphane Chazelas Dec 03 '13 at 06:52
  • @StephaneChazelas yeah: it is a known issue; it'll start responding in a while. – jasonwryan Dec 03 '13 at 07:09