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 linux commands to be executed with root privileges either directly as a root user or by use of
sudo
command - $ – requires given linux commands 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"
tmpfile=/tmp/$location.out
# Obtain sunrise and sunset raw data from weather.com
wget -q "https://weather.com/weather/today/l/$location" -O "$tmpfile"
SUNR=$(grep SunriseSunset "$tmpfile" | grep -oE '((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))' | head -1)
SUNS=$(grep SunriseSunset "$tmpfile" | grep -oE '((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))' | tail -1)
sunrise=$(date --date="$SUNR" +%R)
sunset=$(date --date="$SUNS" +%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.