[jenkins] 파이프 라인의 sh DSL 명령에서 stdout을 캡처 할 수 있습니까?

예를 들면 :

var output=sh "echo foo";
echo "output=$output";

나는 얻을 것이다 :

output=0

그래서 분명히 stdout이 아닌 종료 코드를 얻습니다. stdout을 파이프 라인 변수로 캡처하여 다음과 같은 output=foo
결과를 얻을 수
있습니까?



답변

지금sh스텝 지지체 복귀 표준 출력 파라미터를 제공하여 returnStdout.

// These should all be performed at the point where you've
// checked out your sources on the slave. A 'git' executable
// must be available.
// Most typical, if you're not cloning into a sub directory
gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
// short SHA, possibly better for chat notifications, etc.
shortCommit = gitCommit.take(6)

이 예를 참조하십시오 .


답변

참고 : 연결된 Jenkins 문제는 이후 해결되었습니다.

JENKINS-26133 에서 언급했듯이 쉘 출력을 변수로 얻을 수 없었 습니다. 임시 파일에서 쓰기 읽기 사용을 제안하는 해결 방법입니다. 따라서 귀하의 예는 다음과 같습니다.

sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";


답변

이 시도:

def get_git_sha(git_dir='') {
    dir(git_dir) {
        return sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
    }
}

node(BUILD_NODE) {
    ...
    repo_SHA = get_git_sha('src/FooBar.git')
    echo repo_SHA
    ...
}

테스트 대상 :

  • 젠킨스 버전 2.19.1
  • 파이프 라인 2.4


답변

이 함수를 사용하여 StdErr StdOut 및 리턴 코드를 캡처 할 수도 있습니다.

def runShell(String command){
    def responseCode = sh returnStatus: true, script: "${command} &> tmp.txt"
    def output =  readFile(file: "tmp.txt")

    if (responseCode != 0){
      println "[ERROR] ${output}"
      throw new Exception("${output}")
    }else{
      return "${output}"
    }
}

주의:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name


답변

짧은 버전은 다음과 같습니다.

echo sh(script: 'ls -al', returnStdout: true).result


답변

def listing = sh script: 'ls -la /', returnStdout:true

참고 : http://shop.oreilly.com/product/0636920064602.do 433 페이지


답변

나는 같은 문제가 있었고 잘못된 블록에서 시도하고 있다는 것을 알게 된 후 발견 된 거의 모든 것을 시도했습니다. 환경 블록에 있어야하지만 단계 블록에서 시도했습니다.

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {
                            println my_var
                            }
                }