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

Bitbucket Pipelines中YAML锚点内联Bash脚本语法错误求助

问题

在Bitbucket Pipeline中编写了如下YAML锚点配置:

npm_audit: &npm_audit
    echo "Running npm audit..."
    npm_audit_output=$(npm audit --audit-level=critical)
    if [ $? -ne 0 ]; then
    echo "Critical vulnerabilities found. They must be fixed manually:"
    exit 1
    fi
    npm_audit_output=$(npm audit)
    if [ $? -ne 0 ]; then
    echo "Non-critical vulnerabilities found."
    echo "$npm_audit_output"
    echo "Attempting to fix..."
    npm audit fix
    else
    echo "No vulnerabilities found."
    fi

通过以下方式调用该锚点:

- step:
      ...
      script:
        - *npm_audit

Bitbucket返回错误:

+ echo "Running npm audit..." npm_audit_output=$(npm audit --audit-level=critical) if [ $? -ne 0 ]; then echo "Critical vulnerabilities found. They must be fixed manually:" exit 1 fi npm_audit_output=$(npm audit) if [ $? -ne 0 ]; then echo "Non-critical vulnerabilities found." echo "$npm_audit_output" echo "Attempting to fix..." npm audit fix else echo "No vulnerabilities found." fi
bash: bashScript5261110360543614450.sh: line 5: syntax error near unexpected token `then'

ShellCheck检测该Bash脚本无异常,请问为何会出现语法错误?为何整个脚本被回显而非指定字符串?

原因与解决方法

核心问题:YAML锚点类型不匹配

Bitbucket Pipeline的script字段要求每一项是单个字符串形式的Shell命令,但你定义的锚点&npm_audit是YAML序列(多行命令集合),直接用*npm_audit引用时,YAML会把整个序列合并成单个字符串传入Shell,导致所有命令被拼接成一行执行,既触发语法错误,又让echo把后续所有内容当成参数输出。

解决办法

将锚点定义为多行字符串,用|保留换行符,让Shell能正确识别每条命令:

npm_audit: &npm_audit |
    echo "Running npm audit..."
    npm_audit_output=$(npm audit --audit-level=critical)
    if [ $? -ne 0 ]; then
      echo "Critical vulnerabilities found. They must be fixed manually:"
      exit 1
    fi
    npm_audit_output=$(npm audit)
    if [ $? -ne 0 ]; then
      echo "Non-critical vulnerabilities found."
      echo "$npm_audit_output"
      echo "Attempting to fix..."
      npm audit fix
    else
      echo "No vulnerabilities found."
    fi

调用方式不变,此时YAML会把锚点内容作为带换行的单个字符串传给script,Shell会按换行分割成多条命令执行,语法错误和回显问题都会解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:22:48