简体   繁体   中英

Running sh commands in Jenkins Pipeline with escaping quotes

I am running a shell script within the Jenkins pipeline and i want to print into a text file latest files names column created by date, i dont want want to print time & date column etc, just anything after 9 which are files names and print to into a txt file..

codes are as below:

Note: when i run those commands in bash all work fine, \\ is added as Jenkins does not seems to like the $ without the dollar sign all run fine in shell.

out put in shell is like this:

 bash.sh
        home
        testfile.txt
        blabla.csv
        rtyuioiuytrty.xml

like above I would like to be printed in Jenkinsfile. Jenkins does not seem to like to run those codes as below: I also tried this loop

node ('node') {
    stage ('SSH To server') {
      sshagent(credentials: ['sshkey']) {
        script {
        sh"""ssh -o StrictHostKeyChecking=no user@servername << EOF

      if [ \$? -ne 0 ]; then
                    echo " Error while connecting SSH "
                    exit 1
            fi  

     cd ${SOURCE_PATH}
     if [ \$? -ne 0 ]; then
           echo "Error while doing change directory \${SOURCE_PATH} "
           exit 1
     fi

     ls -lrt | grep "$(date '+%b %e')" |awk '{ s =""; for (i = 9; i <= NF; i++) s = s $i " "; print }'


        exit
        EOF
   """

Welcome to the hell of escaping in Jenkins :-)

probably the below command will help you

node(''){
  sh "touch test.txt"
  sh """ls -lrt | grep \"\$(date '+%b %e')\" |awk '{ s =\"\"; for (i = 9; i <= NF; i++) s = s \$i \" \"; print s }'"""
}

The gist is, you will have to escape double quotes and the dollar.

Answer for your updated code snippet is

 sh"""ssh -o StrictHostKeyChecking=no user@servername << EOF
        if [ \$? -ne 0 ]; then
            echo \" Error while connecting SSH \"
            exit 1
        fi  
        cd \${SOURCE_PATH}
        if [ \$? -ne 0 ]; then
            echo \"Error while doing change directory \${SOURCE_PATH} \"
            exit 1
        fi
        ls -lrt | grep \"\$(date '+%b %e')\" | awk '{ print \\\$9}'
        exit
        EOF
    """

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM