如何在詹金斯管道中运行Shell脚本

时间:2020-09-14 07:10:00

标签: linux shell jenkins jenkins-pipeline

我想从jenkins管道运行shell脚本,而不是调用shell脚本,我可以像下面一样逐个运行sh命令

top -bn1 | grep load | awk '{printf "%.2f%%\t\t\n", $(NF-2)}'
free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }'
iostat -c 3 3 |awk '/^ /{print $4}'|awk  '{ printf( "%s ", $1 ); } END { printf( "\n" ); }'

我是jenkins的新手,但是当我尝试将其与sh结合使用时,就像下面的给出错误一样

pipeline {
    agent any
    stages {
        stage('Check System Usage') {
            steps {
                script {
                     def CPUUSAGE = sh (script: "top -bn1 | grep load | awk '{printf "%.2f%%\t\t\n", $(NF-2)}'", returnStdout: true).trim() as Integer
                     def MEMUSAGE = sh (script:free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }'", returnStdout: true).trim() as Integer
                     def IOWAIT = sh (script:"iostat -c 3 3 |awk '/^ /{print $4}'|awk  '{ printf( "%s ", $1 ); } END { printf( "\n" ); }'", returnStdout: true).trim() as Integer
                     println("CPUUSAGE = ${CPUUSAGE}","MEMUSAGE = ${MEMUSAGE}","IOWAIT = {IOWAIT}")
                }
            }
        }
    }
}

您可以指导在jenkins文件中运行shell命令的确切格式是什么,还是可以共享示例代码以供参考。

2 个答案:

答案 0 :(得分:0)

您使用的“”和“”不正确。

答案 1 :(得分:0)

阅读https://www.jenkins.io/doc/book/pipeline/https://code-examples.net/en/q/237ec14,我会尝试:

pipeline {
    agent any
    stages {
        stage('Check System Usage') {
            steps {
                script {
                    bash'''#!/bin/bash 
                        CPUUSAGE=$(top -bn1 | grep load | awk '{printf "%.2f%%\t\t\n", $(NF-2)}')
                        MEMUSAGE=$(free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }')
                        IOWAIT=$(iostat -c 3 3 |awk '/^ /{print $4}'|awk  '{ printf( "%s ", $1 ); } END { printf( "\n" ); }')
                        echo("CPUUSAGE = ${CPUUSAGE}","MEMUSAGE = ${MEMUSAGE}","IOWAIT = {IOWAIT}")
                    '''
                }
            }
        }
    }
}