Objective

The objective is to use command line and bash shell script to obtain Sunrise & Sunset time information for any given location.

Operating System and Software Versions

  • Operating System: - Linux distribution agnostic.

Requirements

Installed lynx tool and access to shell command line. Your location code obtained from https://weather.codes/search/.

Difficulty

EASY

Conventions

  • # - requires given command to be executed with root privileges either directly as a root user or by use of sudo command
  • $ - given command to be executed as a regular non-privileged user

Instructions

The main motivation for me to get the Sunrise & Sunset times, hence writing this simple script is for a home automation. In my case I would like to start certain devices in times when solar power generation is adequate for device's power requirements. Given that I have a correct Sunrise & Sunset time information and can offset the start end end time with an appropriate number of hours.

Sunrise & Sunset Script

Create a shell scrip eg. sunrise-sunset.sh with a following content:
#!/bin/bash

# First obtain a location code from: https://weather.codes/search/

# Insert your location. For example LOXX0001 is a location code for Bratislava, Slovakia
location="LOXX0001"

# Obtain sunrise and sunset raw data from weather.com
sun_times=$( lynx --dump  https://weather.com/weather/today/l/$location | grep "\* Sun" | sed "s/[[:alpha:]]//g;s/*//" )
# Extract sunrise and sunset times and convert to 24 hour format
sunrise=$(date --date="`echo $sun_times | awk '{ print $1}'` AM" +%R)
sunset=$(date --date="`echo $sun_times | awk '{ print $2}'` PM" +%R)

# Use $sunrise and $sunset variables to fit your needs. Example:
echo "Sunrise for location $location: $sunrise"
echo "Sunset for location $location: $sunset"
Alternatively, you can also clone the latest version from github:
$ git clone https://github.com/linuxconfig/Sunrise-Sunset-Shell-Script.git
Obtain your location code from https://weather.codes/search/ and assign it to location variable while replacing the current example code. Save the file and make it executable:
$ chmod +x sunrise-sunset.sh

Obtain Sunrise & Sunset times

Make sure that lynx command is available on Linux system or run:
UBUNTU/DEBIAN
# apt install lynx
CENTOS/REDHAT
# yum install lynx
to install it. All what has left to to run the script:
$ ./sunrise-sunset.sh 
Sunrise for location LOXX0001: 06:47
Sunset for location LOXX0001: 18:34
I hope you find this script useful as I do.