求助修正带目录切换的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'sstepssection. This ensures all the shell commands in that step block execute within the Backend directory. - Removed the redundant
sh 'cd Backend'line—sincedir()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 (
Buildinstead ofbuild) 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

