Mastering Time Arithmetic in Shell: Add, Subtract, and Compute Differences
This guide explains how to perform time addition, subtraction, and difference calculations in shell scripts by converting dates to timestamps, manipulating seconds, and converting results back to readable formats, complete with practical examples and essential Bash arithmetic operators.
Overview
Shell scripting often requires precise handling of dates and times, such as adding or subtracting intervals and calculating the difference between two timestamps. The following sections demonstrate reliable methods using date and Bash arithmetic.
1. Time Addition and Subtraction
The process consists of three steps: convert the original date to a Unix timestamp, convert the interval to seconds, and add the values together.
a. Convert the base time to a timestamp
time1=$(date +%s -d '1990-01-01 01:01:01')Result:
631126861b. Convert the interval to seconds
# 1 hour 20 minutes = 1*60*60 + 20*60 seconds
time2=$((1*60*60 + 20*60))
# Verify
echo $time2Result:
4800c. Add the timestamps and convert back to a readable date
time1=$(($time1 + $time2))
# Convert Unix timestamp to formatted date
date -d "1970-01-01 UTC $time1 seconds" '+%Y-%m-%d %H:%M:%S'Result:
1990-01-01 02:21:012. Time Difference Calculation
To find the interval between two dates, convert each to a timestamp and subtract.
# Example: difference between 2010-01-01 and 2009-01-01 11:11:11
time1=$(($(date +%s -d '2010-01-01') - $(date +%s -d '2009-01-01 11:11:11')))
# Output the difference in seconds
echo $time1
# Convert to minutes if needed
echo $((time1 / 60))The subtraction yields the total seconds; further division can produce minutes, hours, or days as required.
3. Bash Arithmetic Operators
Shell arithmetic can be performed with single or double parentheses. Single parentheses evaluate a command substitution, while double parentheses compute arithmetic expressions.
# Single parentheses (command substitution)
a=$(date) # equivalent to a=date
# Double parentheses (arithmetic)
a=$((1+2))
echo $a # prints 3
# Using expr as an alternative
a=$(expr 1 + 2)These operators are essential for manipulating numeric values such as timestamps.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
