I need to create a script that will execute daily (cron job), calculate the uptime of the system (days only), and if that number is greater than a defined value (e.g. 30), email the system's information (uname -a) and the number of days to some address (e.g. admin@company.com).

I am getting lost in converting the value of days to something I can perform a calculation on and take action. Started by using the

uptime | grep -o "up.*day"

command but then got stuck. Using CentOS 7.8.

Thank you in advance for any help!

  • 1
    Do you have uptime -s? E.g. uptime in seconds: echo "$(( $(date +'%s') - $(date -d"$(uptime -s)" +'%s') ))". If the value is greater than 3600*24*30, then ...
    – Freddy
    May 15 '20 at 4:24

The documentation man uptime offers this snippet

-s, --since - system up since, in yyyy-mm-dd HH:MM:SS format

So you can get an absolute date/time from which the counting commenced

uptime -s
2020-02-12 12:37:16

Subtract that from the current date/time and you'll get days. (It's a little more fiddly as date maths is usually in seconds)

# Seconds at boot
secSince=$(date --date "$(uptime -s)" +%s)

# Seconds now
secNow=$(date +%s)

# Difference
secInterval=$((secNow - secSince))

# Convert to days
daysInterval=$((secInterval / (60*60*24)))

echo "$daysInterval day(s) uptime"

If there's been a leap second added during the calculated interval the reported day may be off by one within a couple of seconds of your local midnight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.