Human Readable Duration in Bash
Posted by Dave Eddy on Jun 29 2014 - tags: techshow seconds in a human-readable form using pure bash
This function provides a simple way to turn a number of seconds into a human readable form using minutes, hours, days, etc. For example.
$ human 50
50 seconds
$ human 600
10 minutes
$ human 75890
21 hours
$ human 475890
5 days
$ echo "bash has been running for $(human "$SECONDS")"
bash has been running for 2 minutes
The Code
human() {
local seconds=$1
if ((seconds < 0)); then
((seconds *= -1))
fi
local times=(
$((seconds / 60 / 60 / 24 / 365)) # years
$((seconds / 60 / 60 / 24 / 30)) # months
$((seconds / 60 / 60 / 24 / 7)) # weeks
$((seconds / 60 / 60 / 24)) # days
$((seconds / 60 / 60)) # hours
$((seconds / 60)) # minutes
$((seconds)) # seconds
)
local names=(year month week day hour minute second)
local i
for ((i = 0; i < ${#names[@]}; i++)); do
if ((${times[$i]} > 1)); then
echo "${times[$i]} ${names[$i]}s"
return
elif ((${times[$i]} == 1)); then
echo "${times[$i]} ${names[$i]}"
return
fi
done
echo '0 seconds'
}
MIT License