Issue
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.
class="snippet-code">
#!/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'''
Solution
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'''
}
}
}
}
Answered By - Kiruba
Answer Checked By - Katrina (JavaFixing Volunteer)