Jonathin
Jonathin

Reputation: 127

How to translate seconds to minutes & seconds in Bash?

I have a Bash script that downloads files from a website through it's API, and I wanted to implement a thing (for a lack of better words) at the end that would display how long it took for the script to complete. With this code, I was able to do it:

#!/bin/bash
SECONDS=0

# -- Code to Execute --

echo "Task complete"
echo "Script completed in $(echo "scale=2; $SECONDS / 60" | bc) minutes"

However, this would display the time the script took to execute in fractions of a minute:

Task complete
Script completed in 1.35 minutes

How would I be able to translate the amount of seconds the script took to complete into minutes and seconds? Like this:

Task complete
Script completed in 1 minute and 12 seconds

Upvotes: 3

Views: 4604

Answers (3)

dtlam26
dtlam26

Reputation: 1600

Straight forward through awk within a single line:

echo $(seconds) | awk '{printf "%d:%02d:%02d", $1/3600, ($1/60)%60, $1%60}'

Upvotes: 1

codeforester
codeforester

Reputation: 42999

Bash is good at simple integer math:

total_time=100
minutes=$((total_time / 60))
seconds=$((total_time % 60))
echo "Script completed in $minutes minutes and $seconds seconds"
# output -> Script completed in 1 minutes and 40 seconds

Upvotes: 4

Gordon Davisson
Gordon Davisson

Reputation: 125798

You can use the integer division and modulo operators in the shell:

echo "Script completed in $((SECONDS/60)) minutes and $((SECONDS%60)) seconds"

If you want to leave out the seconds and minutes parts if they're zero, it's a little more complicated:

if (( SECONDS/60 == 0 )); then
            echo "Script completed in $SECONDS seconds"
elif (( SECONDS%60 == 0 )); then
    echo "Script completed in $((SECONDS/60)) minutes"
else
    echo "Script completed in $((SECONDS/60)) minutes and $((SECONDS%60)) seconds"
fi

(It'll still say things like "1 minutes" rather than "1 minute"; you could fix that too if you wanted to make it even more complicated...)

Upvotes: 6

Related Questions