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.


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




  • # - 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


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:

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

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

# 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:
# apt install lynx
# 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.
FIND LATEST LINUX JOBS on LinuxCareers.com
Submit your RESUME, create a JOB ALERT.
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
Get extra help by visiting our LINUX FORUM or simply use comments below.

Comments and Discussions
Linux Forum