簡體   English   中英

在Jenkins管道腳本中的Shell腳本中創建文件時出現問題

[英]Issues while create a file in shell scripting in jenkins pipeline script

我正在嘗試使用以下命令在Jenkins管道腳本中創建多行文件。

    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'

不幸的是,我無法創建名為greetings.txt的文件。 任何人都可以讓我知道我要去哪里了。

Jenkins控制台中的結果:

[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

任何的意見都將會有幫助。

謝謝!

它沒有找到一個名為greetings.text的文件,因為您沒有創建一個文件(cat行擴展名中的拼寫錯誤)。 嘗試sh 'cat greetings.txt' ,甚至可以更好地調整腳本:

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'

如果要使用多行命令,還可以使用以下語法:

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

在上一個示例中,這應生成類似以下的輸出:

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

這可以通過在sh使用單引號來解決,因此您無需使用轉義。 另外,您還必須使用>創建初始文件,並使用>>添加內容:

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

輸出:

[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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM