[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Can Bash do simple math?
From: |
Greg Wooledge |
Subject: |
Re: Can Bash do simple math? |
Date: |
Tue, 6 Aug 2024 10:46:57 -0400 |
On Tue, Aug 06, 2024 at 16:35:39 +0200, alex xmb sw ratchev wrote:
> On Tue, Aug 6, 2024, 00:34 <bash@blaklinten.xyz> wrote:
>
> > I have a somewhat strange issue.
> > In a script I use the `((VAR = expression ))` syntax to calculate a
> > simple remainder by division:
> >
> > ((DIFF = $2 - $1))
> > ((SECONDS = DIFF % 60))
> > ((MINUTES = (DIFF % 3600) / 60))
> > ((HOURS = DIFF / 3600))
> >
>
> just .. what u do diff % 60 , 'SECONDS' it is already .. % 60 ( if it
> counts as how many 60thiet times ) is minutes already
> i suppose u mean $2(seconds) -1(seconds) , = seconds
> if thats not ur case plz explain
The code is converting a (large) number of seconds into a time interval
expressed as a number of hours, plus a number of minutes, plus a number
of seconds.
There are a few different ways to perform this calculation. The most
straightforward IMHO would be:
1) Divide the total by 3600 to get the number of hours.
2) Decrease the total by (3600*hours).
3) Divide the new total by 60 to get the number of minutes.
4) Decrease the total by (60*minutes).
5) The remaining total is the number of seconds.
The poster is using a slight variant, in which the number of hours and
the number of seconds are calculated directly from the total, and the
number of minutes is calculated directly from the total in two steps,
without modifying the total or introducing an explicit temporary variable.
1) The number of seconds is the total mod 60.
2) The number of hours is the total divided by 3600.
3) The number of minutes is computed by first taking the total mod 3600
(which removes the whole hours), and then dividing that by 60.
There is an *implicit* temporary variable in step 3, but it's not given
a name or a formal storage allocation.
- Re: Can Bash do simple math?, (continued)
Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
- Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
- Re: Can Bash do simple math?,
Greg Wooledge <=
- Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
- Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
- Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
- Re: Can Bash do simple math?, Bash-help, 2024/08/06
- Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
Re: Can Bash do simple math?, Greg Wooledge, 2024/08/06
Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06
Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06