I'm running into an issue where my script will only set the integer that I need for the variable $alive
if I allow the following error to show.
uptime: /dev/ttys001: No such file or directory
I've attempted to remove this by adding &>/dev/null
either behind uptime
or behind the command in this context below,
(( uptime | grep -ohe 'up .*' | sed 's/,//g' | awk '{ print $2 }')&>/dev/null)
or
( uptime &>/dev/null | grep -ohe 'up .*' | sed 's/,//g' | awk '{ print $2 }')
but this causes the following to happen
This computer has been awake for days
whereas I need it to set the variable and perform like so
This computer has been awake for 32 days
This is more of a personal project for me to understand scripting using bash within MacOS so any additional insight is greatly appreciated!
Here is the script in its context. It is intended to be an infinite loop to keep the computer on for remote access at all times and can be stopped by simply terminating the running process.
#!/bin/bash
alive=$( uptime | grep -ohe 'up .*' | sed 's/,//g' | awk '{ print $2 }')
until [[ $alive -lt 0 ]]; do
Caffeinate -d -t 2
sleep 2
echo "This computer has been awake for $alive days"
done
Eventually I'd like to have the computer hit a certain amount of days, then break and restart, automatically login, and launch the process over again to ensure that performance is not hindered by the computer being awake for months on end.
But I haven't had the time to work on that just yet ;)
uptime
's output will vary. Less than a day will print the hours elapsed, more than that it will printtimenow up x days, ...
. – annahri Jul 20 '21 at 06:30