Last active
May 18, 2023 11:55
-
-
Save gandli/6d59916fe9e49eecc98280aba083f84d to your computer and use it in GitHub Desktop.
set_wallpaper.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 配置 | |
DEFAULT_DOWNLOAD_DIR="$HOME/Pictures" | |
LOG_FILE="/usr/local/bin/set_wallpaper.log" | |
# 等待10秒钟,确保网络连接已经建立 | |
sleep 10 | |
# 获取bing壁纸JSON响应 | |
image_data=$($(which curl) -s 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1') | |
# 异常处理 | |
if [ -z "$image_data" ]; then | |
echo "$(date '+%Y-%m-%d %H:%M:%S') - 错误: 无法从Bing API获取壁纸信息" >>$LOG_FILE | |
exit 1 | |
fi | |
# 提取urlbase | |
urlbase=$(echo "$image_data" | grep -oE 'urlbase":"[^"]+"' | cut -d'"' -f3) | |
# 生成不同分辨率图片URL | |
image_url_UHD="https://cn.bing.com${urlbase}_UHD.jpg" | |
# image_url_HD="https://cn.bing.com${urlbase}_1920x1080.jpg" | |
# image_url_SD="https://cn.bing.com${urlbase}_768x768.jpg" | |
# 提取fullstartdate并生成图片文件名 | |
title=$(echo "$image_data" | grep -oE 'title":"[^"]+"' | cut -d'"' -f3) | |
full_date=$(echo "$image_data" | grep -oE 'fullstartdate":"[^"]+"' | cut -d'"' -f3) | |
filename="$full_date-$title.jpg" | |
# 配置下载目录 | |
download_dir=${1:-$DEFAULT_DOWNLOAD_DIR} | |
# 查询图片是否已经下载 | |
if [ ! -f "$download_dir/$filename" ]; then | |
# 图片未下载,下载图片 | |
/usr/bin/curl -s -L -o "$download_dir/$filename" "$image_url_UHD" | |
else | |
echo "图片已下载!" | |
fi | |
# 等待10秒钟,确保图片下载完成 | |
sleep 10 | |
# 查询壁纸是否已经设置当天图片 | |
wallpaper_path=$(osascript -e 'tell application "Finder" to get desktop picture as POSIX file') | |
if [ "$wallpaper_path" != "$download_dir/$filename" ]; then | |
# 壁纸未设置,设置壁纸 | |
osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$download_dir/$filename\"" | |
else | |
echo "壁纸已设置!" | |
fi | |
# 记录日志 | |
echo "$(date '+%Y-%m-%d %H:%M:%S') - $filename" >>$LOG_FILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment