I am writing a script in bash to calculate the time elapsed for the execution of my commands, consider:
STARTTIME=$(date +%s)
#command block that takes time to complete...
#........
ENDTIME=$(date +%s)
echo "It takes $($ENDTIME - $STARTTIME) seconds to complete this task..."
I guess my logic is correct however I end up with the following print out:
"It takes seconds to complete this task..."
Anything wrong with my string evaluation?
I believe bash variables are untyped, I would love if there is a "string to integer" method in bash nevertheless.
I find it very clean to use the internal variable "$SECONDS"
SECONDS=0 ; sleep 10 ; echo $SECONDS
Try the following code:
Either
$(())
or$[]
will work for computing the result of an arithmetic operation. You're using$()
which is simply taking the string and evaluating it as a command. It's a bit of a subtle distinction. Hope this helps.As tink pointed out in the comments on this answer,
$[]
is deprecated, and$(())
should be favored.You can use Bash's
time
keyword here with an appropriate format stringHere's what the reference says about
TIMEFORMAT
: