Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 325
Jonathin Avatar asked Dec 13 '25 21:12

Jonathin


2 Answers

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...)

like image 89
Gordon Davisson Avatar answered Dec 16 '25 13:12

Gordon Davisson


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
like image 31
codeforester Avatar answered Dec 16 '25 14:12

codeforester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!