Hello everyone,
I calculate in my bash script the different between two timestamps in seconds. The next step would be to get the difference in minutes, and there is my Problem:
AnzahlUeberstunden=$(( $(date -d "$JAHR-$MONAT-$TAG $ArbeitEnde" +%s) - $(date -d "$JAHR-$MONAT-$TAG $NormalesArbeitsEnde" +%s) ))
This is the code I calculate the seconds. Normally I would say that I only need to do: AnzahlUeberstunden=$Anzahueberstunden/60
but when I print this I get: 2040/60
What am I doing wrong? The count of seconds is right with 2040......
Thanks for all hints
Steve
Try the same as de line above with $(( ... ))
en some corrections in the variable name..
AnzahlUeberstunden=$((AnzahlUeberstunden/60))
or
(( AnzahlUeberstunden/=60 ))
Why do i have to put tags around it?
Because it is a an arithmetic operation (you are trying to divide a number by 60)
Therefore you need an arithmetic expansion ( see: Shell command language: arithmetic expansions )
so you can assign the result of the arithmetic expression to a variable (assignment means variable=value
)
If you do not do that, in your example AnzahlUeberstunden=$AnzahlUeberstunden/60
what happens is that you assign the value of AnzahlUeberstunden concatenated with the text string /60
, so the result becomes 2040/60
.
--
My second suggestion is called an arithmetic expression (which can be used in shells like ksh93, bash, zsh) in which variables can be modified without an explicit variable assignment.
1 Like
Hi
look at this way
declare -i AnzahlUeberstunden
AnzahlUeberstunden=$(date -d "$JAHR-$MONAT-$TAG $ArbeitEnde" +%s)-$(date -d "$JAHR-$MONAT-$TAG $NormalesArbeitsEnde" +%s) #"tags" are not needed
AnzahlUeberstunden=AnzahlUeberstunden/60 #dollar sign is not needed
echo $AnzahlUeberstunden
34
Please note there should not be spaces around the minus sign
2 Likes
Hi Chaos_Lord...
Just an observation; you have shown figures that apparently create a true integer value on integer division...
What happens if the number of seconds is not fully divisible by 60?
Do you just want the integer division, round down and/or round up, or a floating point value?
One could also use quotes:
AnzahlUeberstunden="$(date -d "$JAHR-$MONAT-$TAG $ArbeitEnde" +%s) - $(date -d "$JAHR-$MONAT-$TAG $NormalesArbeitsEnde" +%s)"
AnzahlUeberstunden='AnzahlUeberstunden / 60'
2 Likes