web-dev-qa-db-ja.com

パイプラインのsh DSLコマンドから標準出力をキャプチャすることは可能ですか?

例えば:

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

私は取得します:

output=0

だから、どうやら私は標準出力ではなく終了コードを取得します。 stdoutをパイプライン変数にキャプチャして、結果としてoutput=fooを取得することは可能ですか?

66
Jesse S

注:リンクされたJenkinsの問題はその後解決されました。

JENKINS-261 で述べたように、シェル出力を変数として取得することはできませんでした。回避策として、一時ファイルからのwrit-readの使用を提案しました。したがって、例は次のようになります。

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

Nowsh step は、パラメータreturnStdoutを指定することでstdoutを返すことをサポートします。

// 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)

この例 を参照してください。

177
iloahz

これを試して:

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
4
METAJIJI

短いバージョンは次のとおりです。

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

この関数を使用して、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
1
GalloCedrone