Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Converting bash script to zsh for converting bytes to 'readable'
- X-seq: zsh-users 23626
- From: Daniel Shahaf <d.s@xxxxxxxxxxxxxxxxxx>
- To: TJ Luoma <luomat@xxxxxxxxx>
- Subject: Re: Converting bash script to zsh for converting bytes to 'readable'
- Date: Wed, 12 Sep 2018 23:08:42 +0000
- Cc: Zsh-Users List <zsh-users@xxxxxxx>
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= daniel.shahaf.name; h=cc:content-transfer-encoding:content-type :date:from:in-reply-to:message-id:mime-version:references :subject:to:x-me-sender:x-me-sender:x-sasl-enc; s=fm1; bh=C2WLxR PmubP0b50zsu7kFgVuyeXr5eOtgNjfnsR3uZU=; b=nDHmozQdH0RQtEXztMspCu uqJSmO88v17NMvtjmuNM03QOwyjup8yLx41cFzud0DItNzkboUKTUhfJVfQX4r5F BBPSyUX8AwEeNVqygv3TvSFZyLynM+c3kUBjX+OTHJIb9H68tV/DIC4jLdaDlTD+ dZCFOXma82DbHmfXyEtLjjB68KQzS98wWsEDkGAt9NtCtLCHenmH7KMpGnmDt/CW 8qRMUUPqccn4x7xnJ+xVCHb3JiJQbX/6y+1Wdi/oNJowG6jO1Ju/MIyeTbrIve6k wD6CuaGlADR4tOrWV2mTasn2EPRI19CFlHPE6mcb6L+yDZcFmB6J+tjJ2SAXabWA ==
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:content-transfer-encoding:content-type :date:from:in-reply-to:message-id:mime-version:references :subject:to:x-me-sender:x-me-sender:x-sasl-enc; s=fm3; bh=C2WLxR PmubP0b50zsu7kFgVuyeXr5eOtgNjfnsR3uZU=; b=RUmtgfNziKZ9DkWBZrBwur LjVt8nhIzvJ8onvzIQvFjav8eEg1/sssJYX5z+4whx6EUoowfOoh7qFM+JQS6LRz v7EnhH+nVXu36oyCYoV3piDiV45DftAr9YjDz/q5EfiZnSVNioW4tz+YJBe94+4H xXiYufa9n30jTSzQ63mqoW7UtW6nn7tAm8yz7h1wLTnmzlzAv0JjVbyOhMaURq0g plcUVUFJl8ia8ZtgxTX03GWqwfrIUS9proY/BKHvCuUbd38qJ14Ruv/d5F4RXxeS Y3a6QvMP7HvW+cd72i4zXeLbNEZdO7Fy6Xh9FhIF8owemZWWWMEZDiTqvg/6qVAA ==
- In-reply-to: <20180912230445.fpfihe7htuqkfbed@tarpaulin.shahaf.local2>
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- List-unsubscribe: <mailto:zsh-users-unsubscribe@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
- References: <CADjGqHtKCEc-cwrQXOtjVSrYE6U+tpP5aYWrfd9prrVmvOKrtg@mail.gmail.com> <20180912230445.fpfihe7htuqkfbed@tarpaulin.shahaf.local2>
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