I have the below shell script that i need to echo to a file lets say script.sh from a groovy interface like Jenkinsfile but keep getting compilation errors.
#!/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
I tried the below :-
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'''
You can try using writeFile option to write the content into file, but in your case you have to escape backslash alone in your script. Below should work.
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'''
}
}
}
}
To write your script into a file use the writeFile step (see here ). This will create a file in your workspace from a string.
In a declarative pipeline it looks something like this:
writeFile(file: "fileName", text: "Your Script")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.