Bash script to calculate time elapsed

2019-03-07 20:01发布

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.

标签: linux bash shell
8条回答
在下西门庆
2楼-- · 2019-03-07 21:05

try using time with the elapsed seconds option:

/usr/bin/time -f%e sleep 1 under bash.

or \time -f%e sleep 1 in interactive bash.

see the time man page:

Users of the bash shell need to use an explicit path in order to run the external time command and not the shell builtin variant. On system where time is installed in /usr/bin, the first example would become /usr/bin/time wc /etc/hosts

and

FORMATTING THE OUTPUT
...
    %      A literal '%'.
    e      Elapsed  real  (wall  clock) time used by the process, in
                 seconds.
查看更多
ら.Afraid
3楼-- · 2019-03-07 21:06

You are trying to execute the number in the ENDTIME as a command. You should also see an error like 1370306857: command not found. Instead use the arithmetic expansion:

echo "It takes $(($ENDTIME - $STARTTIME)) seconds to complete this task..."

You could also save the commands in a separate script, commands.sh, and use time command:

time commands.sh
查看更多
登录 后发表回答