编写Shell脚本获取Docker Desktop最新版本失败,是curl还是正则问题?
Docker Desktop版本号获取脚本失败排查
我正在Pop!_OS上编写Shell脚本,用来先安装Docker Desktop的前置依赖,再自动安装最新版,主要是为了练习Shell脚本编写。尝试了两种方案都没成功:
尝试1
#!/bin/bash # get the latest version number latest_version=$(curl -s https://docs.docker.com/desktop/release-notes/ | grep -oP '(?<=#)[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?' | head -n 1) printf "$latest_version"
结果:脚本无任何输出
尝试2
#!/bin/bash # get the latest version number version=$(curl -s https://docs.docker.com/desktop/release-notes/ \ | grep -oE '/desktop/release-notes/#[0-9]+\.[0-9]+\.[0-9]+' \ | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' \ | sort -rn \ | head -n 1) # check if version number is empty if [ -z "$version" ]; then echo "Unable to retrieve the latest version number." exit 1 fi
结果:脚本输出"Unable to retrieve the latest version number."
问题原因
既不是curl的限制问题,核心是正则表达式匹配不上当前网页的结构。Docker的release notes页面结构会随版本更新调整,你写的正则是基于旧版页面的元素格式,现在页面里的版本号锚点、标签结构已经变化,导致grep无法匹配到目标内容:
- 尝试1的正向预查正则,目标版本号的锚点不再是纯文本里直接的
#x.x.x格式,而是被包裹在HTML标签属性中(比如<h2 id="25.0.3">),纯文本匹配抓不到; - 尝试2里的
/desktop/release-notes/#x.x.x路径在当前页面中已不存在,自然匹配不到内容。
修正方案
方案1:调整正则适配当前页面结构
直接匹配HTML标签中的版本号属性,比如:
#!/bin/bash latest_version=$(curl -s https://docs.docker.com/desktop/release-notes/ | grep -oP '(?<=id=")[0-9]+\.[0-9]+\.[0-9]+' | head -n 1) if [ -z "$latest_version" ]; then echo "Unable to retrieve the latest version number." exit 1 fi echo "Latest Docker Desktop version: $latest_version"
方案2:用专业HTML解析工具(更可靠)
安装pup(一款轻量HTML解析工具)后,通过元素选择器精准提取版本号,避免正则匹配HTML的不稳定:
#!/bin/bash latest_version=$(curl -s https://docs.docker.com/desktop/release-notes/ | pup 'h2[id^="2"] text{}' | head -n 1) # 这里id^="2"是因为当前Docker Desktop主版本号为2开头,可根据后续版本调整 if [ -z "$latest_version" ]; then echo "Unable to retrieve the latest version number." exit 1 fi echo "Latest Docker Desktop version: $latest_version"
内容的提问来源于stack exchange,提问作者Vegas588
相关产品推荐
相关产品推荐

