Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash expr calculation with variables (cygwin)

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)
like image 742
Matthias Avatar asked Dec 07 '25 12:12

Matthias


2 Answers

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
like image 164
anubhava Avatar answered Dec 10 '25 11:12

anubhava


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.

like image 26
Matthias Avatar answered Dec 10 '25 12:12

Matthias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!