Corentin
Corentin

Reputation: 325

why subtraction return - symbol

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 ?

Upvotes: 0

Views: 112

Answers (2)

paxdiablo
paxdiablo

Reputation: 882028

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)

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

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)

Upvotes: 5

Related Questions