You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本验证文件指定行内容的语法错误与匹配问题排查

问题:验证SQL输出文件指定行内容的Bash脚本问题

需求

执行后续操作前,需验证ij生成的SQL输出文件的指定行内容:确保第5行是-----------,第6行是1。

原始脚本及报错

最初编写的Bash脚本:

if sed -n '5p' $SQLFILE == "-----------" && sed -n '6p' $SQLFILE == "1";;
then
print "Success\n\n"
else
printf "Failure\n\n"
exit 200
fi

执行时报错:syntax error near -n

修改后的调试输出

修改后开启-x调试的输出:

++ sed -n 5p ./testsql.txt
+ '[' ----------- == ----------- ']'
++ sed -n 6p ./testsql.txt
+ '[' '1          ' == 1 ']'
+ printf 'Initial Datasource Not Found, Or Error Running SQL Script. Exiting\n\n'

直接执行sed命令的结果

[rvp@linuxtest UtilitiesTests]# sed -n '5p' $SQLFILE
-----------
[rvp@linuxtest UtilitiesTests]# sed -n '6p' $SQLFILE
1

问题核心

修改后的脚本因第6行实际存在多余空格(调试输出可见为1 ),导致字符串匹配失败,需解决该Bash条件判断问题。


解决方案

1. 修复原始脚本语法错误

原始if语句存在语法问题:Bash中字符串比较需用[ ... ]或[[ ... ]]包裹,==运算符两边必须有空格,且if语句结尾不能用;;。

2. 处理行尾空格问题

以下几种方式可解决行尾多余空格导致的匹配失败:

方法一:提取时用sed去除行尾空白

在提取行内容的同时,用sed命令删除行尾所有空白字符:

if [[ $(sed -n '5p;s/[[:space:]]*$//' "$SQLFILE") == "-----------" && $(sed -n '6p;s/[[:space:]]*$//' "$SQLFILE") == "1" ]]; then
    printf "Success\n\n"
else
    printf "Failure\n\n"
    exit 200
fi

方法二:用tr删除提取内容中的空白

将提取的行内容通过tr命令删除所有空白字符后再比较:

line5=$(sed -n '5p' "$SQLFILE" | tr -d '[:space:]')
line6=$(sed -n '6p' "$SQLFILE" | tr -d '[:space:]')

if [[ "$line5" == "-----------" && "$line6" == "1" ]]; then
    printf "Success\n\n"
else
    printf "Failure\n\n"
    exit 200
fi

方法三:用[[ ... ]]的模式匹配忽略后续空格

利用[[ ... ]]支持的模式匹配,直接匹配以1开头的行:

if [[ $(sed -n '5p' "$SQLFILE") == "-----------" && $(sed -n '6p' "$SQLFILE") == "1"* ]]; then
    printf "Success\n\n"
else
    printf "Failure\n\n"
    exit 200
fi

注意事项

  • 变量$SQLFILE需用双引号包裹,避免文件名含空格时出现解析错误。
  • 优先使用[[ ... ]]进行条件判断,相比[ ... ]更灵活,支持模式匹配且无需转义特殊字符。

内容的提问来源于stack exchange,提问作者Tedford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:27:34