简体   繁体   中英

Issues while create a file in shell scripting in jenkins pipeline script

I am trying to create a multi line file in Jenkins pipeline script using the below commands.

    sh "echo \"line 1\" >> greetings.txt"
    sh "echo \"line 2\" >> greetings.txt"
    echo "The contents of the file are"
    sh 'cat greetings.text'
    sh 'rm -rf greetings.txt'

Unforunately , I am not able to create the file named greetings.txt. Can any one please let me know, where I am going wrong.

Results in Jenkins console:

[tagging] Running shell script
+ echo 'line 1'
[Pipeline] sh
[tagging] Running shell script
+ echo 'line 2'
[Pipeline] echo
The contents of the file are
[Pipeline] sh
[tagging] Running shell script
+ cat greetings.text
cat: greetings.text: No such file or directory

Any suggestions would be helpful.

Thanks!

It's not finding a file named greetings.text because you didn't create one (a litte typo in the extension in your cat line). Try sh 'cat greetings.txt' , or even better adjusted your script:

sh "echo \"line 1\" >> greetings.txt"
sh "echo \"line 2\" >> greetings.txt"
echo "The contents of the file are"
sh 'cat greetings.txt'
sh 'rm -rf greetings.txt'

If you want to use multiline commands, you can also use this syntax:

sh """
echo \"line 1\" >> greetings.txt
echo \"line 2\" >> greetings.txt
echo "The contents of the file are:"
cat greetings.txt
rm -rf greetings.txt
"""

From the last example, this should generate an output like:

Running shell script
+ echo 'line 1'
+ echo 'line 2'
+ echo 'The contents of the file are:'
The contents of the file are:
+ cat greetings.txt
line 1
line 2
+ rm -rf greetings.txt

This can be solve this by using single quotes with sh , so you don't need to use escaping. Also you have to create an initial file with > and add content with >> :

pipeline{
    agent any

    stages{
        stage('write file'){
            steps{
                sh 'echo "line 1" > greetings.txt'
                sh 'echo "line 2" >> greetings.txt'
                echo "The contents of the file is"
                sh 'cat greetings.txt'
                sh 'rm -rf greetings.txt'
            }
        }
    }
}

output:

[test] Running shell script
+ echo line 1
[Pipeline] sh
[test] Running shell script
+ echo line 2
[Pipeline] echo
The contents of the file is
[Pipeline] sh
[test] Running shell script
+ cat greetings.txt
line 1
line 2
[Pipeline] sh
[test] Running shell script
+ rm -rf greetings.txt
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

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