added support for parsing days in uptime

This commit is contained in:
Russel Yasol
2024-05-13 20:52:13 +08:00
parent acc37fd937
commit 06b84b48a4

View File

@@ -3,19 +3,43 @@
# Execute the uptime command and extract the uptime duration # Execute the uptime command and extract the uptime duration
uptime_output=$(uptime) uptime_output=$(uptime)
# Extract hours and minutes from the uptime string # Example output of the uptime command
# 2 days, 14:08,
# Extract days, hours and minutes from the uptime string
# For days, match if day or days is present in the string
if [[ "$uptime_output" =~ day ]]; then
days=$(echo "$uptime_output" | awk -F '[ ,]+' '{print $2}')
else
days=0
fi
hours=$(echo "$uptime_output" | awk -F '[ :]+' '{print $6}') hours=$(echo "$uptime_output" | awk -F '[ :]+' '{print $6}')
minutes=$(echo "$uptime_output" | awk -F '[ :]+' '{print $7}') minutes=$(echo "$uptime_output" | awk -F '[ :]+' '{print $7}')
# Check if days is empty, then set it to 0
if [ -z "$days" ]; then
days=0
fi
# Remove comma to days
days=$(echo $days | tr -d ,)
# Remove comma to minutes # Remove comma to minutes
minutes=$(echo $minutes | tr -d ,) minutes=$(echo $minutes | tr -d ,)
# Create a text response with the uptime duration # Create a text response with the uptime duration. If days is empty, then set it to 0
uptime_text="$hours hours and $minutes minutes" uptime_text="$days days, $hours hours, $minutes minutes"
# if hours and minutes are 1 or 0, then remove the 's' from the end of the string # If days is 0, then remove it from the text response
if [ $hours -eq 1 ] || [ $hours -eq 0 ]; then if [ "$days" -eq 0 ]; then
uptime_text=$(echo $uptime_text | sed 's/hours/hour/g') uptime_text="$hours hours, $minutes minutes"
fi
# if days and hours are 0 or 1, remove s from the end of the string
if [ "$days" -eq 0 ] && [ "$hours" -eq 0 ] || [ "$days" -eq 1 ] && [ "$hours" -eq 1 ]; then
uptime_text=$(echo $uptime_text | sed 's/s//g')
fi fi
# Set header for plain text content # Set header for plain text content