Подтвердить что ты не робот

Можно ли захватить stdout из команды sh DS sh в конвейере

Например:

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

Я получу:

output=0

Итак, я, видимо, получаю код выхода, а не stdout. Можно ли записать stdout в переменную конвейера, чтобы я мог получить: output=foo как мой результат?

4b9b3361

Ответ 1

Примечание: связанная проблема Jenkins с тех пор была решена.

Как упоминалось в JENKINS-26133, было невозможно получить вывод оболочки в виде переменной. В качестве обходного пути предлагается использовать запись-чтение из временного файла. Итак, ваш пример выглядел бы так:

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

Ответ 2

Теперь, sh шаг поддерживает возврат stdout путем подачи параметра 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)

См. этот пример.

Ответ 3

Попробуйте следующее:

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
  • Pipeline 2.4

Ответ 4

Короткая версия будет:

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

Ответ 5

Вы также можете попытаться использовать эти функции для захвата 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