Save in a variable the number of seconds a process took to run

后端 未结 5 684
走了就别回头了
走了就别回头了 2021-02-04 17:15

I want to run a process in bash and save in an env variable the number of seconds it took to run. How would I do such a thing?

5条回答
  •  天涯浪人
    2021-02-04 18:02

    Are you wanting to put this code in your script, or do it from the process that starts the script?

    For the latter, you can use the "time" reserved word and then parse what it returns to get how much time a script takes.

    If you want to do this from within a script you can set the variable SECONDS to zero, and each time thereafter that you reference that variable it will be updated to be the number of elapsed seconds. So, you can put "SECONDS=0" at the very start of your script, and whenever you need the elapsed time it will be in the SECONDS variable.

    You can also use the $SECONDS trick on the command line as well, for example:

    $ SECONDS=0; sleep 5 ; echo "that took approximately $SECONDS seconds"
    

    The time reserved word and the SECONDS variable are both documented in the bash man page.

提交回复
热议问题