반응형

 

 젠킨스(Jenkins)에서 sh 명령어를 사용하여 명령을 실행하고, 그 결과를 stdout으로 화면에 출력하려면 다음과 같이 파이프라인 스크립트를 작성할 수 있습니다.

 파이프라인의 script 블록 안에 sh 명령어를 사용하고, returnStdout 옵션을 사용하면 됩니다.

다음은 예시입니다:

예시 1.  sh(..) 명령어를 이용하여 쉘 스크립트 실행

 

더보기
pipeline {
    agent any

    stages {
        stage('Run Shell Command') {
            steps {
                script {
                    // 쉘 명령을 실행하고, 결과를 변수에 저장
                    def result = sh(script: 'echo "Hello, Jenkins!"', returnStdout: true).trim()

                    // 결과를 화면에 출력
                    echo "Command output: ${result}"
                }
            }
        }
    }
}

 

 

이 스크립트는 다음과 같은 작업을 수행합니다:

1. sh 스텝을 사용하여 echo "Hello, Jenkins!" 명령을 실행합니다.
2. returnStdout: true 옵션을 사용하여 명령어의 출력 결과를 캡처합니다.
3. 캡처된 출력 결과를 result 변수에 저장하고, echo 스텝을 사용하여 화면에 출력합니다.

이 방식으로 원하는 쉘 명령어를 sh 스텝에 넣고 returnStdout 옵션을 사용하면 그 결과를 캡처하고 화면에 출력할 수 있습니다.

 

예시 2. 쉘 커맨드를 변수에 넣고 출력하는 방법

 

더보기
pipeline {
    agent any

    stages {
        stage('Run Shell Command with Variable') {
            steps {
                script {
                    // 쉘 명령어를 변수에 저장
                    def shellCommand = 'echo "Hello, Jenkins!"'

                    // 변수에 저장된 쉘 명령어를 실행하고, 결과를 변수에 저장
                    def result = sh(script: shellCommand, returnStdout: true).trim()

                    // 결과를 화면에 출력
                    echo "Command output: ${result}"
                }
            }
        }
    }
}

 

 

예시 3. 쉘 스크립트 여러줄 실행하는 방법

 

더보기

pipeline {
    agent any

    stages {
        stage('Run Multiple Shell Commands with Variable') {
            steps {
                script {
                    // 여러 줄의 쉘 명령어를 변수에 저장
                    def shellCommand = '''
                        echo "Hello, Jenkins!"
                        echo "Running multiple commands"
                        ls -la
                    '''

                    // 변수에 저장된 쉘 명령어를 실행하고, 결과를 변수에 저장
                    def result = sh(script: shellCommand, returnStdout: true).trim()

                    // 결과를 화면에 출력
                    echo "Command output: ${result}"
                }
            }
        }
    }
}

 

반응형