[英]How to pass groovy variable to shell script in Jenkinsfile?
[英]How to echo a shell script to a file in groovy interface like Jenkinsfile
我有下面的 shell 腳本,我需要將它回顯到一個文件中,讓我們從 Jenkinsfile 這樣的 groovy 界面說 script.sh,但不斷收到編譯錯誤。
#!/bin/bash commit_hash=$(git rev-parse HEAD) parent_hashes=`git rev-list --parents -n 1 $commit_hash` parent_count=`wc -w <<< $parent_hashes` if [[ $parent_count -gt 2 ]] then p=`git name-rev $parent_hashes | xargs -0 | grep -e '^\\S\\+ master$'` if [[ ! -z $p ]] then echo "merged branch is master" exit 0 else echo "merged branch is anything but master" exit 2 fi else echo "no branch merged" exit 1 fi
我嘗試了以下:-
sh '''echo '#!/bin/bash commit_hash=$(git rev-parse HEAD) parent_hashes=`git rev-list --parents -n 1 $commit_hash` parent_count=`wc -w <<< $parent_hashes` if [[ $parent_count -gt 2 ]] then p=`git name-rev $parent_hashes | xargs -0 | grep -e '^\\S\\+ master$'` if [[ ! -z $p ]] then echo "merged branch is master" exit 0 else echo "merged branch is anything but master" exit 2 fi else echo "no branch merged" exit 1 fi' > script.sh'''
您可以嘗試使用 writeFile 選項將內容寫入文件,但在您的情況下,您必須在腳本中單獨轉義反斜杠。 下面應該工作。
pipeline {
agent any
stages {
stage ("Test") {
steps{
writeFile file:'test.txt', text: '''#!/bin/bash
commit_hash=$(git rev-parse HEAD)
parent_hashes=`git rev-list --parents -n 1 $commit_hash`
parent_count=`wc -w <<< $parent_hashes`
if [[ $parent_count -gt 2 ]]
then
p=`git name-rev $parent_hashes | xargs -0 | grep -e '^\\S\\+ master$'`
if [[ ! -z $p ]]
then
echo "merged branch is master"
exit 0
else
echo "merged branch is anything but master"
exit 2
fi
else
echo "no branch merged"
exit 1
fi'''
}
}
}
}
要將腳本寫入文件,請使用 writeFile 步驟(請參閱此處)。 這將從字符串在您的工作區中創建一個文件。
在聲明性管道中,它看起來像這樣:
writeFile(file: "fileName", text: "Your Script")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.