bash expr 计算变量(cygwin)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5990504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash expr calculation with variables (cygwin)
提问by Matthias
I am trying to calculate the difference between two unix timestamps. The calculation of 42-23 is for testing purposes only.
我正在尝试计算两个 unix 时间戳之间的差异。42-23 的计算仅用于测试目的。
# !/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:
从另一个变量中减去一个变量有什么问题?该脚本正在使用 unix 机器。我在 Windows 7 上使用 Cygwin:
$ 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)
回答by Matthias
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.
问题是我在 Windows 上编写了脚本,其系统特定的行结尾是\r\n
. 更改为 Unix 行结尾后\n
,它可以工作。
回答by anubhava
You don't need to call expr
for this actually just use bash's $(( expr ))
feature. On my cygwin this code is working fine:
您expr
实际上不需要调用此$(( expr ))
功能,只需使用 bash 的功能即可。在我的 cygwin 上,这段代码运行良好:
# !/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 (-)}'
And it gave this output:
它给出了这个输出:
B: 8316
8316
回答by tmg
Why not use $[] ?
为什么不使用 $[] ?
TARGET=1305281500
CURRENT=1305281554
A=$[42 - 23]
B=$[$TARGET - $CURRENT]
echo "A: $A"
echo "B: $B"
输出:A: 19
B: -54
回答by Chang Peng
I don't see this problem on Linux here. But do you get the right answer with the line
我在这里在 Linux 上没有看到这个问题。但是你能得到正确的答案吗?
B=`expr $TARGET - $CURRENT`
replaced by
取而代之
B=`eval expr $TARGET - $CURRENT`