why subtraction return - symbol

懵懂的女人 提交于 2021-02-05 11:18:04

问题


I have a problem with a simple subtraction but I don't understand what's wrong.

My code :

start= date +%s%N | cut -b1-13
#Treatment...
end= date +%s%N | cut -b1-13

delta=`expr $end - $start`
echo "delta $delta"

My console display :

  1374652348283
  ...
  1374652349207
  delta -

My question is : Why do I got a - symbol returned ?


回答1:


The command:

a= b

(note the space) will set a to an empty string while it runs the command b. It's a way to temporarily set environment variables for a single command, things like:

PATH=/path/to/somwhere gcc whatever  # Here, PATH has the modified value.
echo $PATH                           # Here, PATH has its original value.

So the command line:

start= date +%s%N | cut -b1-13

sets start temporarily to nothing and runs the date command. Hence both start and end are still empty when you use them, which is why you only get the -, since expr - just gives you -.

If you want to get the results of the date command into a variable, use:

start=$(date +%s%N | cut -b1-13)



回答2:


You didn't assign to the variables. You must not have spaces around the equals sign.

Also, you're doing it wrong.

start=$(date +%s%N | cut -b1-13)


来源:https://stackoverflow.com/questions/17828392/why-subtraction-return-symbol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!