2

I'm trying to work out the difference in 2 unix times to do a simple calculation (in a shell script) but it doesn't seem to work.

I have set 2 variables one called $d and the other $c.

Here's the syntax i currently have for setting up the variables:

c= echo $a | awk -F : '{print ($1 * 32140800) + ($2 * 2678400) + ($3 * 86400) + ($4 * 3600) + ($5 * 60) }'
echo $c
d= echo $a | awk -F : '{print ($1 * 32140800) + ($2 * 2678400) + ($3 * 86400) + ($4 * 3600) + ($5 * 60) }'
echo $d

(variables a and b simply receive the timestamp from another script)

I'm trying to subtract the output of $c from $d but every method I have used doesn't seem to work.

I've tried the following: 1)

duration=$(echo "$d - $c")
echo $duration 

2)

duration=$((d-c))
echo $duration 
ilkkachu
  • 138,973
SSR
  • 25

2 Answers2

5
c= echo $a | awk -F : '{print ($1 * 32140800) + ($2 * 2678400) + ($3 * 86400) + ($4 * 3600) + ($5 * 60) }'

You're missing the command substitution here. This will just run the echo | awk pipeline, while setting c to the empty value in the environment of echo.

You used a command substitution below, in duration=$(echo "$d - $c"), that's what you need here, too. i.e.

c=$(echo "$a" | awk  ...)

(Note that there's no whitespace around the = sign, that's what separates a plain assignment from a command, see Spaces in variable assignments in shell scripts)

Also, looking at the numbers in the awk script, you seem to have 31-day months, and accordingly 372-day years, which may or may not be what you want. If your input has seconds too, the awk script doesn't use them. (Should there be a + $6 in the end?) There's also $a in both commands, instead of $a and $b.

duration=$(echo "$d - $c")

This would just set duration to a string like 5678 - 1234 (with the actual values of d and c) since echo just prints what was given, it doesn't do arithmetic.

duration=$((d-c))

This should work to do the subtraction.

ilkkachu
  • 138,973
  • Thank you so much! It makes sense that the variables i have been setting for c and d is an empty value now (as the calculation has been returning nothing when executed) – SSR Nov 07 '19 at 13:42
  • @SSR, note that if you run c= echo, or c=foo echo, it only sets c for the duration of the echo. The assignment is only permanent if there's no actuall command to run on the same command line. Here, it doesn't show, an undefined variable acts pretty much the same as one assigned an empty string. – ilkkachu Nov 07 '19 at 16:31
2

What shell are you using ? Arithmetic isn't implemented in the old-school /bin/sh but works pretty fine with bash:

~$ a=10000000
~$ b=200
~$ echo $((a-b))
9999800
binarym
  • 2,649
  • Hi, I'm using bash. I tried your solution alone and it worked but for some reason the syntax doesn't work on the variables that I have already set – SSR Nov 07 '19 at 13:33