Skip to content

Instantly share code, notes, and snippets.

@luckman212
Created May 3, 2024 13:56
Show Gist options
  • Save luckman212/a46f62f247bfcf46ba03faf83f3b88cb to your computer and use it in GitHub Desktop.
Save luckman212/a46f62f247bfcf46ba03faf83f3b88cb to your computer and use it in GitHub Desktop.
poor man's uptime on macOS by parsing JSON output of system_profiler
system_profiler SPSoftwareDataType -json |
jq --raw-output --argjson labels '[ "day", "hour", "minute", "second" ]' '
.SPSoftwareDataType[0].uptime[3:] // empty | split(":") as $uptime |
def pprint:
($uptime[.] | tonumber) as $val |
if $val == 0 then empty else
"\($val) \($labels[.])" + (if $val == 1 then "" else "s" end)
end;
[range($uptime|length)] | map(pprint) | join(", ")'
@luckman212
Copy link
Author

luckman212 commented May 3, 2024

Localization example

You can localize the strings by modifying the labels string passed in via --argjson... e.g. Spanish

jq --raw-output --argjson labels '[ "día", "hora", "minuto", "segundo" ]' ...

Output:

2 días, 9 horas, 52 minutos, 34 segundos

Another example, showing ONLY hours:

system_profiler SPSoftwareDataType -json |
jq --raw-output --argjson labels '[ "day", "hour", "minute", "second" ]' '
.SPSoftwareDataType[0].uptime[3:] // empty | split(":") as $uptime |

def pprint:
  ($uptime[.] | tonumber) as $val |
  "\($val) \($labels[.])" + (if $val == 1 then "" else "s" end);

[1] | map(pprint) | join(", ")'

Output:

12 hours

Another example: calculate and display uptime in the form of seconds

system_profiler SPSoftwareDataType -json |
jq --raw-output '
.SPSoftwareDataType[0].uptime[3:] // empty |
split(":") | map(tonumber) as $uptime |
[86400, 3600, 60] as $multipliers |
reduce range($uptime|length) as $i (0; . + ($uptime[$i] * ($multipliers[$i] // 1)))'

Output

216416

@luckman212
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment