Re: Misleading text: $(()) is not bash specific

Christian Franke <[email protected]>
Newsgroups gmane.linux.utilities.smartmontools
Message-ID <[email protected]>
Chris Down wrote:
> Hello,
>
> In the "RETURN VALUES" section of the manual page for smartctl(8), it is
> stated:
>
>         To test within the shell for whether or not the different bits
>         are turned on or off, you can use the following type of
>         construction (this is bash syntax):
>         smartstat=$(($? & 8))

Yes, this should work with any POSIX shell.


>         This bash script prints all status bits:
>         status=$?
>         for ((i=0; i<8; i++)); do
>           echo "Bit $i: $((status & 2**i && 1))"
>         done
>
> All references to bash should be removed and replaced with notes that
> this is instead *POSIX* shell syntax -- this code works in all POSIX
> shells. See section 2.6.4 of POSIX[0].
>
> Perhaps this was confused with `((', which is indeed not POSIX (although
> it is also not bash-specific).

No, the exponentiation operator (2**i) is also not part of POSIX. The 
script is actually bash specific:

$ for sh in bash dash mksh posh zsh; do $sh -c 'echo $((2**4))'; done
16
dash: 1: arithmetic expression: expecting primary: "2**4"
mksh: 2**4: unexpected '*'
posh: 2**4: unexpected `*'
16

On FreeBSD with default shell:
$ echo $((2**4))
arithmetic expression: syntax error: "2**4"

A check of the "for ((.;.;.))" loop gives similar results.

(BTW: The script does also not work with zsh due to different op 
precedence and the R/O status variable)


It would probably make sense to use a more portable example, e.g.:

val=$?; mask=1
for i in 0 1 2 3 4 5 6 7; do
   echo "Bit $i: $(((val & mask) && 1))"
   mask=$((mask << 1))
done


Thanks,
Christian


------------------------------------------------------------------------------
CenturyLink Cloud: The Leader in Enterprise Cloud Services.
Learn Why More Businesses Are Choosing CenturyLink Cloud For
Critical Workloads, Development Environments & Everything In Between.
Get a Quote or Start a Free Trial Today. 
http://pubads.g.doubleclick.net/gampad/clk?id=119420431&iu=/4140/ostg.clktrk
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.