How to Display Your “Uptime” using Bash



Bash is a powerful scripting tool and comes in handy on more than one occasion. Here is a fun one: Write your server uptime to a text file so that you can display it on a webpage.

#!/bin/sh

# get the uptime data
days=$(uptime | awk '{print $3}' | sed 's/,//g')
hours=$(uptime | awk '{print $5}' | sed 's/,//g')
label=$(uptime | awk '{print $4}')

if [ "$days" = 1 ]; then
day_label='day'
else
day_label='days'
fi

#format labels
if [ $hours = 1 ]; then
hour_label='hour'
else
hour_label='hours'
fi

#format output
if [ "$label" = 'mins,' ]; then
echo 'This server has been on for '$days minutes'' > /var/www/uptime.txt
elif [[ "$label" = 'day,' || "$label" = 'days,' ]]; then
echo 'This server has been on for '$days $day_label, $hours $hour_label'' > /var/www/uptime.txt
elif [ "$label" = '2' ]; then
echo 'This server has been on for '$days hours'' > /var/www/uptime.txt
fi

Related posts:

  1. Display the Contents of a File Using PHP
  2. April Fool’s Batch File
  3. Display Novell Servers Connected to Your Server
  4. Redirect Users Back to Page They Were On
  5. Using PHP code in Posts & Pages

Comments