Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Converting bash script to zsh for converting bytes to 'readable'



Daniel Shahaf wrote on Wed, Sep 12, 2018 at 23:04:45 +0000:
>      1	zmodload zsh/mathfunc
>      2	f() {
>      3	  setopt localoptions ksharrays
>      4	  integer i=$(( log2( $1 )/10 )) 
>      5	  local -a SI=( '' 'Ki' 'Mi' 'Gi' )
>      6	  printf '%5.2g %s\n' "$(( ($1)*1.0 / (1<<(10*i)) ))" "${SI[i]}B"
>      7	}

A subtle point here: in an arithmetic expression, using raw variable names
behave as one'd expect, but using variable expansions does not.  Compare:

% s='1+1'
% echo $(( s * 2 )) 
4
% echo $(( $s * 2 ))
3
% 

That's why I put parentheses around the «$1» in the math expression: that
ensures consistent parsing even if $1 is an expression (as in «f "1024+1024"»).

Cheers,

Daniel
(It's exactly the same issue as with C macros)



Messages sorted by: Reverse Date, Date, Thread, Author