I want to write a script in bash that will save to file how long it have been executed
I want output to look like this:
1 minute
2 minute
...
I want to write a script in bash that will save to file how long it have been executed
I want output to look like this:
1 minute
2 minute
...
You need to install time
(not the shell built-in).
To validate that you have the right one: $ which time
This is the expected output:
$ which time
/usr/bin/time
Assuming that you have a function called main
, in which your main scripting code is included
function main() {
echo "Sleeping .."
sleep(5)
echo "This is the first arg: ${1}"
echo "This is the second arg: ${2}"
}
To time this function call, do as follows (arguments for reference):
main "HELLO" "WORLD" | $(which time) -o "OUTPUT_FILENAME_FOR_TIME" -f "%e" $(which bash)
We are piping /usr/bin/time to the function call to time it. We are calling time
using $(which time)
because we do not want the shell built-in. After that we are passing the -o
argument to define our output file and then the -f
argument is used to define the time format. In my example, I used seconds. In the end, we pass which shell we are using, and in our case we are using bash, so $(which bash)
.
man time
to read about other formats and of course the proper usage of the programI always use seconds because it is easier to convert them to anything.
You can use the GNU tool command
instead of using the absolute path of time
$ command time
instead of
$ $(which time)