如何从Linux命令行获取任何位置的日出和日落时间如何从Linux命令行获取任何位置的日出和日落时间如何从Linux命令行获取任何位置的日出和日落时间如何从Linux命令行获取任何位置的日出和日落时间
  • 业务
  • 目标
  • 支持
  • 登录
找到的结果: {phrase} (显示: {results_count} 共: {results_count_total})
显示: {results_count} 共: {results_count_total}

加载更多搜索结果...

搜索范围
模糊匹配
搜索标题
搜索内容

如何从Linux命令行获取任何位置的日出和日落时间

发表 admin at 2025年2月28日
类别
  • 未分类
标签

客观的

目标是使用命令行和 bash shell 脚本获取任何给定位置的日出和日落时间信息。

操作系统和软件版本

  • 操作系统: – Linux 发行版不可知。

要求

安装了 lynx 工具并访问 shell 命令行。您的位置代码是从 https://weather.codes/search/ 获取的。

困难

简单的

惯例

  • # – 要求以root权限直接以root用户身份或使用sudo命令执行给定的linux命令

  • $ – 要求以常规非特权用户身份执行给定的 Linux 命令

指示

我获取日出和日落时间的主要动机,因此编写这个简单的脚本是为了家庭自动化。就我而言,我希望在太阳能发电足以满足设备电力需求时启动某些设备。鉴于我有正确的日出和日落时间信息,并且可以将开始结束时间偏移适当的小时数。

日出和日落脚本

创建一个 shell 脚本,例如。 sunrise-sunset.sh 包含以下内容:

#!/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"

或者,您也可以从 github 克隆最新版本:

$ git clone https://github.com/linuxconfig/Sunrise-Sunset-Shell-Script.git

从 https://weather.codes/search/ 获取您的位置代码,并将其分配给 location 变量,同时替换当前示例代码。保存文件并使其可执行:

$ chmod +x sunrise-sunset.sh

获取日出和日落时间

确保 lynx 命令在 Linux 系统上可用或运行:

UBUNTU/DEBIAN
# apt install lynx
CENTOS/REDHAT
# yum install lynx

安装它。剩下的就是运行脚本:

$ ./sunrise-sunset.sh 
Sunrise for location LOXX0001: 06:47
Sunset for location LOXX0001: 18:34

我希望您像我一样发现这个脚本很有用。

©2015-2025 Norria support@norria.com