From: Eric Blake Date: Tue, 6 May 2008 15:31:55 +0000 (-0600) Subject: Document $(( )) pitfalls. X-Git-Tag: v2.63~88 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=2811da8583226d60b8082852f8f6085e8c47bd3d;p=thirdparty%2Fautoconf.git Document $(( )) pitfalls. * doc/autoconf.texi (Shell Substitutions): Mention octal vs. decimal. Mention autotest's at_func_arith. Signed-off-by: Eric Blake --- diff --git a/ChangeLog b/ChangeLog index 59a311916..c2d0f17ac 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,9 @@ 2008-05-06 Eric Blake + Document $(( )) pitfalls. + * doc/autoconf.texi (Shell Substitutions): Mention octal + vs. decimal. Mention autotest's at_func_arith. + Improve behavior of './testsuite 01'. * lib/autotest/general.m4 (AT_INIT) : Alter usage to eval its arguments, in order to normalize away diff --git a/doc/autoconf.texi b/doc/autoconf.texi index a5e880ac1..cd9a38982 100644 --- a/doc/autoconf.texi +++ b/doc/autoconf.texi @@ -13203,6 +13203,44 @@ echo $(case x in x) echo hello;; esac) Arithmetic expansion is not portable as some shells (most notably Solaris 10 @command{/bin/sh}) don't support it. +Among shells that do support @samp{$(( ))}, not all of them obey the +Posix rule that octal and hexadecimal constants must be recognized: + +@example +$ @kbd{bash -c 'echo $(( 010 + 0x10 ))'} +24 +$ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'} +26 +$ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'} +24 +$ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'} +pdksh: 010 + 0x10 : bad number `0x10' +$ @kbd{pdksh -c 'echo $(( 010 ))'} +10 +@end example + +When it is available, using arithmetic expansion provides a noticeable +speedup in script execution; but testing for support requires +@command{eval} to avoid syntax errors. If shell function support has +also been detected, then this construct can be used to assign @samp{foo} +to an arithmetic result, provided all numeric arguments are provided in +decimal and without a leading zero: + +@example +if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then + eval 'func_arith () + @{ + func_arith_result=$(( $* )) + @}' +else + at_func_arith () + @{ + func_arith_result=`expr "$@@"` + @} +fi +func_arith 1 + 1 +foo=$func_arith_result +@end example @item ^