How to translate seconds to minutes & seconds in Bash?

0

Issue

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

Solution

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

Answered By – codeforester

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More