zsh-users
 help / color / mirror / code / Atom feed
From: Daniel Shahaf <d.s@daniel.shahaf.name>
To: TJ Luoma <luomat@gmail.com>
Cc: Zsh-Users List <zsh-users@zsh.org>
Subject: Re: Converting bash script to zsh for converting bytes to 'readable'
Date: Wed, 12 Sep 2018 23:08:42 +0000	[thread overview]
Message-ID: <20180912230842.db66mgh3px2rsbru@tarpaulin.shahaf.local2> (raw)
In-Reply-To: <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)

      reply	other threads:[~2018-09-12 23:09 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2018-09-12 22:02 TJ Luoma
2018-09-12 22:38 ` TJ Luoma
2018-09-12 22:52   ` Bart Schaefer
2018-09-12 23:04 ` Daniel Shahaf
2018-09-12 23:08   ` Daniel Shahaf [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20180912230842.db66mgh3px2rsbru@tarpaulin.shahaf.local2 \
    --to=d.s@daniel.shahaf.name \
    --cc=luomat@gmail.com \
    --cc=zsh-users@zsh.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).