0

In my bash script, I want to print the time that my set of commands took to execute.

I'm doing this:

#!/bin/bash
start=$(date +%s)
./my-long-command.sh
./another-longcommand.sh
echo "Completed, in $(echo "$(date +%s) - ${start}" | bc)s"

It prints, for example:

Completed, in 450s

I want it to print milliseconds, or seconds, or minutes, or hours -- depending on the value. Also, I don't want to write a complex expression for bc in every script, where I need to print such a time difference. Are you aware of any tdiff command in Linux, which would enable this:

echo "Completed, in $(tdiff ${start})"

Please, don't suggest creating my own script for this.

1

1 Answer 1

1

There's a builtin variable for this:

#!/bin/bash
./my-long-command.sh
./another-longcommand.sh
echo "Completed, in ${SECONDS}s"

Please, don't suggest creating my own script for this.

Why not? It's not that complex:

tdiff() {
    if (($1 < 60)); then
        printf '%ds' "$1"
    elif (($1 < 60*60)); then
        printf '%dm' $(($1 / 60))
        tdiff $(($1 % 60))
    else
        printf '%dh' $(($1 / (60*60)))
        tdiff $(($1 % (60*60)))
    fi
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .