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

求助修正带目录切换的Jenkins Pipeline语法错误

Hey Alexander, let's get your Jenkins Pipeline sorted out—you're close, just a small tweak with how you're using the dir() step!

The main issue in your script is that in Declarative Pipeline, the stages block can only contain stage elements directly. You wrapped entire stages with dir(), which isn't allowed. Also, that sh 'cd Backend' in your Test stage won't affect the following sh commands because each sh runs in its own separate shell session.

Here's the fixed version of your Pipeline:

pipeline { 
    agent { docker { image 'node' args '-p 5000:5000' } } 
    stages { 
        stage('Build') { 
            steps {
                dir("Backend") { 
                    sh 'pwd' 
                    sh 'echo start build' 
                    sh 'ls' 
                    sh 'npm install' 
                }
            }
        } 
        stage('Test') { 
            steps {
                dir("Backend") { 
                    sh 'echo start test' 
                    sh 'ls' 
                    sh 'npm run test' 
                }
            }
        } 
    } 
}

Let me break down the changes:

  • Moved the dir("Backend") blocks inside each stage's steps section. This ensures all the shell commands in that step block execute within the Backend directory.
  • Removed the redundant sh 'cd Backend' line—since dir() handles the directory switch across all subsequent steps in its block, this line was doing nothing useful (and wouldn't persist across shell sessions anyway).
  • Capitalized the stage names (Build instead of build) for readability—this is a convention, not a requirement, but it makes your Pipeline easier to scan.

This should work exactly as you intended: switching to the Backend directory for both the Build and Test stages, running your Node.js commands there.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:07:48