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
相关产品推荐
相关产品推荐

