Ashley
Ashley

Reputation: 1629

How to echo a shell script to a file in groovy interface like Jenkinsfile

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'''
I see the shell script has single quotes in a line plus a few back slashes, so not sure why groovy is not allowing normal shell interpolation here. How do i get to echo the contents of this shell script to a file using groovy. I am trying this out in scripted Jenkinsfile.

Upvotes: 0

Views: 5507

Answers (2)

Kiruba
Kiruba

Reputation: 1377

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'''
            }
        }
    }
}

Upvotes: 1

Steve
Steve

Reputation: 71

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

Upvotes: 0

Related Questions