运行两年的Bash内核版本比较脚本突发整数比较语法错误
内核版本检查脚本语法错误排查与解决
问题背景
以下是用于Linux内核补丁版本更新时编译安装内核的Bash逻辑:
post_kernel_postinst() { # 提取新内核和当前内核版本 NEW_KV=$(eselect kernel show | tail -n 1 | grep -oE '[0-9\.]{5,7}') CURRENT_KV=$(uname -r | grep -oE '[0-9\.]{5,7}') # 将版本字符串拆分为数组 IFS='.' read -r -a NEW_KV_ARR <<< "$NEW_KV" IFS='.' read -r -a CURRENT_KV_ARR <<< "$CURRENT_KV" # 获取补丁版本号 NEW_KERNEL_PATCH_VERSION="${NEW_KV_ARR[2]}" CURRENT_KERNEL_PATCH_VERSION="${CURRENT_KV_ARR[2]}" echo "NEW_KV $NEW_KV" echo "CURRENT_KV $CURRENT_KV" echo "NEW_KERNEL_PATCH_VERSION $NEW_KERNEL_PATCH_VERSION" echo "CURRENT_KERNEL_PATCH_VERSION $CURRENT_KERNEL_PATCH_VERSION" # 检查新内核版本是否高于当前版本 if [[ $((NEW_KERNEL_PATCH_VERSION - CURRENT_KERNEL_PATCH_VERSION)) -ge 0 ]]; then echo "GoodBye!!" fi }
该脚本正常运行两年多,但近两个月触发如下语法错误:
NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 bash: 3: syntax error: invalid arithmetic operator (error token is "")
两年未修改脚本,无法确定系统哪项变更引发问题。
排查过程
感谢各位帮助,已为eselect添加--color=no参数移除颜色转义字符,但问题仍存在。修改脚本添加函数调用后,发现不同执行方式结果不一致:
修改后的脚本:
post_kernel_postinst() { # 提取新内核和当前内核版本 NEW_KV=$(eselect --color=no kernel show | tail -n 1 | grep -oE '[0-9\.]{5,7}') CURRENT_KV=$(uname -r | grep -oE '[0-9\.]{5,7}') # 将版本字符串拆分为数组 IFS='.' read -r -a NEW_KV_ARR <<< "$NEW_KV" IFS='.' read -r -a CURRENT_KV_ARR <<< "$CURRENT_KV" # 获取补丁版本号 NEW_KERNEL_PATCH_VERSION="${NEW_KV_ARR[2]}" CURRENT_KERNEL_PATCH_VERSION="${CURRENT_KV_ARR[2]}" echo "NEW_KV $NEW_KV" echo "CURRENT_KV $CURRENT_KV" echo "NEW_KERNEL_PATCH_VERSION $NEW_KERNEL_PATCH_VERSION" echo "CURRENT_KERNEL_PATCH_VERSION $CURRENT_KERNEL_PATCH_VERSION" # 检查新内核版本是否高于当前版本 if [[ $((NEW_KERNEL_PATCH_VERSION - CURRENT_KERNEL_PATCH_VERSION)) -ge 0 ]]; then echo "GoodBye!!" fi } post_kernel_postinst
执行输出:
greninja@ash ~ $ source ./temp.sh NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 bash: 3: syntax error: invalid arithmetic operator (error token is "") greninja@ash ~ $ post_kernel_postinst NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 bash: 3: syntax error: invalid arithmetic operator (error token is "") greninja@ash ~ $ ./temp.sh NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 GoodBye!!
最终解决
为grep添加--color=no参数后问题解决,感谢@Charles_Duffy建议使用set -x发现grep默认启用--color=always,以及@benschumacher指出问题源于多余字符。
解决后输出:
greninja@ash ~ $ source ./temp.sh NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 GoodBye!! greninja@ash ~ $ post_kernel_postinst NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 GoodBye!! greninja@ash ~ $ ./temp.sh NEW_KV 6.14.3 CURRENT_KV 6.14.3 NEW_KERNEL_PATCH_VERSION 3 CURRENT_KERNEL_PATCH_VERSION 3 GoodBye!!
内容的提问来源于stack exchange,提问作者GreninjaShuriken4
相关产品推荐
相关产品推荐

