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

Windows环境下Jenkins Pipeline执行sh 'npm install'失败求助

Windows环境下Jenkins Pipeline执行sh命令报错找不到nohup的解决方法

问题原因

sh是Jenkins用于执行类Unix系统shell命令的步骤,它依赖类Unix系统特有的nohup命令维持后台进程,但Windows系统默认没有该命令,因此执行时会触发找不到文件的错误。

解决方案

方案一:替换sh为Windows原生bat步骤

直接将所有sh命令替换为Windows原生的bat步骤,适配Windows环境:

修改后的完整Pipeline脚本:

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://github.com/0APOCALYPSE0/ngrx-task.git'
            }
        }
        stage('Test') {
            steps {
                bat 'npm install'
                bat 'ng test --watch=false'
            }
        }
        stage('Build') {
          steps {
            bat 'ng build'
          }
        }
        stage('Deploy') {
            steps {
                bat 'move dist\\ngrx-task\\*.* C:\\nginx\\'
            }
        }
    }
}

注:ng test添加--watch=false参数可避免交互式窗口导致Jenkins任务卡住。

方案二:实现跨平台兼容(适用于多环境场景)

如果Pipeline需要同时支持Windows和Linux代理,可通过isUnix()条件判断自动切换命令类型:

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://github.com/0APOCALYPSE0/ngrx-task.git'
            }
        }
        stage('Test') {
            steps {
                script {
                    if (isUnix()) {
                        sh 'npm install'
                        sh 'ng test --watch=false'
                    } else {
                        bat 'npm install'
                        bat 'ng test --watch=false'
                    }
                }
            }
        }
        stage('Build') {
          steps {
            script {
                isUnix() ? sh 'ng build' : bat 'ng build'
            }
          }
        }
        stage('Deploy') {
            steps {
                script {
                    if (isUnix()) {
                        sh 'cp -r dist/ngrx-task/* /usr/share/nginx/html/'
                    } else {
                        bat 'move dist\\ngrx-task\\*.* C:\\nginx\\'
                    }
                }
            }
        }
    }
}

额外注意事项

  • 确保Jenkins代理机器已安装Node.js和Angular CLI,并将它们的安装路径添加到系统环境变量中,保证npm和ng命令能直接调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:33:21