irongit
hygoland/scripts/UptimeNixOS.sh
33 lines805 BBourne Again Shell (bash)
1#!/usr/bin/env bash
2# Script parses /proc/uptime to get the system uptime
3# and prints it in a human-readable format
4# This is a workaround for system where `uptime` command is taken from coreutils
5# where `uptime -p` is not supported
6
7if [[ -r /proc/uptime ]]; then
8 s=$(< /proc/uptime)
9 s=${s/.*}
10else
11 echo "Error UptimeNixOS.sh: Uptime could not be determined." >&2
12 exit 1
13fi
14
15d="$((s / 60 / 60 / 24)) days"
16h="$((s / 60 / 60 % 24)) hours"
17m="$((s / 60 % 60)) minutes"
18
19# Remove plural if < 2.
20((${d/ *} == 1)) && d=${d/s}
21((${h/ *} == 1)) && h=${h/s}
22((${m/ *} == 1)) && m=${m/s}
23
24# Hide empty fields.
25((${d/ *} == 0)) && unset d
26((${h/ *} == 0)) && unset h
27((${m/ *} == 0)) && unset m
28
29uptime=${d:+$d, }${h:+$h, }$m
30uptime=${uptime%', '}
31uptime=${uptime:-$s seconds}
32
33echo "up $uptime"