2

I am trying to calculate the difference between two unix timestamps. The calculation of 42-23 is for testing purposes only.

# !/bin/bash
TARGET=1305281500
CURRENT=`date +%s`
echo $TARGET
echo $CURRENT
A=`expr 42 - 23`
B=`expr $TARGET - $CURRENT`
echo "A: $A"
echo "B: $B"

Output:

1305281500
1305281554
expr: non-integer argument
A: 19
B:

What is the problem with subtracting one variable from another? The script is working on a unix maschine. I am using Cygwin on Windows 7:

$ uname -a
CYGWIN_NT-6.1-WOW64 mypcname 1.7.9(0.237/5/3) 2011-03-29 10:10 i686 Cygwin

$ bash --version
GNU bash, version 4.1.10(4)-release (i686-pc-cygwin)
2
  • What bash version, as displayed by bash --version are you on?
    – user2100815
    May 13, 2011 at 10:58
  • @Neil I am using bash version 4.1.10(4)
    – Matthias
    May 13, 2011 at 11:06

4 Answers 4

4

You don't need to call expr for this actually just use bash's $(( expr )) feature. On my cygwin this code is working fine:

# !/bin/bash
TARGET=1305281500
CURRENT=`date +%s`
echo $TARGET
echo $CURRENT
B=$((CURRENT - TARGET))
echo "B: $B"
# For validation only
echo "$TARGET $CURRENT" | awk '{print ($2-$1)}'

And it gave this output:

B: 8316
8316
4

The problem was that I wrote the script on Windows with its system-specific line ending \r\n. After changing to the Unix line ending \n, it works.

3

Why not use $[] ?

TARGET=1305281500
CURRENT=1305281554
A=$[42 - 23]
B=$[$TARGET - $CURRENT]
echo "A: $A"
echo "B: $B"
output:
A: 19
B: -54

1
  • 2
    There is no benefit in using the non-standard $[...] instead of the standard $((...)).
    – jilles
    May 13, 2011 at 12:12
1

I don't see this problem on Linux here. But do you get the right answer with the line

B=`expr $TARGET - $CURRENT`

replaced by

B=`eval expr $TARGET - $CURRENT`
1
  • Unfortunately, this did not work. Maybe it's more a problem with cygwin or my x64 architecture...
    – Matthias
    May 13, 2011 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.