开发者

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 $TA开发者_Python百科RGET
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)


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


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.


Why not use $[] ?

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


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`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜