Skip to content

Instantly share code, notes, and snippets.

@smithje
Forked from matthewmcvickar/current_moon_phase.md
Last active June 3, 2024 01:19
Show Gist options
  • Save smithje/5312617 to your computer and use it in GitHub Desktop.
Save smithje/5312617 to your computer and use it in GitHub Desktop.

Calculate the phase of the moon in bash and get the appropriate icon. This can be used to put a picture of the phase of the moon in your bash prompt.

I used the "Simple" lunar phase calculator from here:

http://www.ben-daglish.net/moon.shtml

It seems to work well on OSX. The call to date that I use is not portable to linux or solaris since date is one of the most infuriatingly inconsistent utilities.

#!/bin/bash
get_phase_day () {
local lp=2551443
local now=$(date -ju +"%s")
local newmoon=592500
local phase=$((($now - $newmoon) % $lp))
echo $(((phase / 86400) + 1))
}
get_moon_icon () {
local phase_number=$(get_phase_day)
# Multiply by 100000 so we can do integer comparison. Go Bash!
local phase_number_biggened=$((phase_number * 100000))
if [ $phase_number_biggened -lt 184566 ]; then phase_icon="πŸŒ‘" # new
elif [ $phase_number_biggened -lt 553699 ]; then phase_icon="πŸŒ’" # waxing crescent
elif [ $phase_number_biggened -lt 922831 ]; then phase_icon="πŸŒ“" # first quarter
elif [ $phase_number_biggened -lt 1291963 ]; then phase_icon="πŸŒ”" # waxing gibbous
elif [ $phase_number_biggened -lt 1661096 ]; then phase_icon="πŸŒ•" # full
elif [ $phase_number_biggened -lt 2030228 ]; then phase_icon="πŸŒ–" # waning gibbous
elif [ $phase_number_biggened -lt 2399361 ]; then phase_icon="πŸŒ—" # last quarter
elif [ $phase_number_biggened -lt 2768493 ]; then phase_icon="🌘" # waning crescent
else phase_icon="πŸŒ‘" # new
fi
echo $phase_icon
}
get_moon_icon
@treasuretron
Copy link

treasuretron commented May 12, 2020

I wonder why you turn a small int into a big int to do comparisons instead of rounding the phase numbers to int size? Say phase_number is 15. You save a step by just asking if 15 is < 16 instead of multiplying 15 by 100000 and asking if 1500000 < 1661096. Though perhaps I'm not fully grasping what's going on :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment