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

Bitbucket Bash脚本报错:`then`附近存在意外语法错误

解决Bitbucket流水线Bash脚本then语法错误问题

问题根源

你使用了YAML的>折叠块语法,这个标记会将所有换行符转换为空格,导致原本的多行Bash脚本被合并成一行。比如开头的declare -a appsArr和后续的if语句直接连在一起,变成declare -a appsArr if [ $Foo == 'deploy' ]; then ...,Bash无法识别这种无分隔符的连续命令,因此抛出then附近的语法错误。

修复方案

将YAML中的>替换为|-,这个标记会保留原有的换行符,让Bash能正确解析每一行命令:

script:
  - |-
    declare -a appsArr
    if [ "$Foo" == 'deploy' ]; then appsArr+=("foo"); fi
    if [ ${#appsArr[@]} -gt 0 ]; then
      AppsJoined=$(printf ", %s" "${appsArr[@]}")
      AppsFinal=${AppsJoined:1}
    fi
    if [ -z "$AppsFinal" ]; then
      echo "No apps selected, exiting..."
      exit 1
    fi
    echo "Will build and deploy following apps:"
    mkdir tmp && echo "${AppsFinal}" | tee tmp/bar.txt

额外优化建议:

  • 给变量$Foo和$AppsFinal添加双引号,避免变量为空时触发语法问题(即便你说明$Foo始终有值,这也是脚本编写的良好习惯)
  • 将if [ ${#appsArr[@]} ]; then调整为if [ ${#appsArr[@]} -gt 0 ]; then,让数组长度判断更规范,避免部分Bash版本的兼容性问题
  • 移除|&,因为echo不会输出错误信息,用|即可满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:40:03