$(()) vs. `expr`

Just a quick note on the relative speed of $(()) vs. expr as a means of evaluating arithmetic expressions in bash: even though they’re (apparently) functionally equivalent, this:

for i in {1..10}; do n=expr $i + 10; echo $n; done

Takes about a full second to run (I can see it print the lines one at a time), whereas this:

for i in {1..10}; do n=$(($i + 10)); echo $n; done

pops out all at once. Tested in GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu).

Comments (2)

  1. Mærk

    I realise this is a little late, but…

    The two forms are not equivalent. The backtick form will invoke a subshell [1] and run the expr program in that environment, while the $(()) form will invoke standard POSIX arithmetic expansion [2] within the current shell context. No subshell means no syscalls, hence the speed boost.

    The {1..10} range expansion is also unfortunately non-standard.
    Unfortunately it looks like seq is non-standard, so the more portable form below isn’t necessarily available (it’s certainly non-functional on some ancient solaris box):

    for i in $(seq 1 10); do n=$(($i + 10)); echo $n; done

    [1] http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03
    [2] http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_04

    Reply
    1. williamberg (Post author)

      Thanks for the info, Mark; good to have some input from a genuine keernel hacker.

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *