Reputation: 4240
I want to time in seconds for execution of shell script.
My implementation:
#!/bin/sh
START=$(date +%s)
echo $START
.
.
bla bla bla
.
.
.
END=$(date +%s)
echo $END
DIFF=($END - $START)
echo "Time difference is "$DIFF
This is showing me END time and not difference. I cannot guess the reason why minus is not working.
Upvotes: 1
Views: 73
Reputation: 753725
You need dollar double parentheses for arithmetic:
DIFF=$(($END - $START))
As in:
#!/bin/bash
START=$(date +%s)
echo $START
sleep 2
END=$(date +%s)
echo $END
DIFF=$(($END - $START))
echo "Time difference is" $DIFF
Bash Reference Manual says:
3.5.5 Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$(( expression ))
The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, command substitution, and quote removal. Arithmetic expansions may be nested.
3.2.4.2 Conditional Constructs
((…))
(( expression ))
The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to
let "expression"
See Bash Builtins, for a full description of the let builtin.
Upvotes: 1
Reputation: 28029
Assuming you're using bash
:
You need to use double parens to do arithmetic in the shell:
((DIFF = START - END))
#or
DIFF=$((START - END))
Note that you don't have to use dollar signs to read from variables inside of double parens.
Upvotes: 2