简体   繁体   English

Shell Jenkins作业从带变量的文件中读取文本

[英]Shell Jenkins job reading text from file with variables

I am implementing Jenkins job in bash shell script. 我正在bash shell脚本中实现Jenkins作业。 Jenkins jobs is using the variable AS_OF_DATE which can be used as input for users. Jenkins作业正在使用变量AS_OF_DATE ,该变量AS_OF_DATE用户的输入。

I also have some files on zone with text that I grep during the execution of this jenkins job. 在执行此jenkins作业期间,我在区域中也有一些带有grep文本的文件。

So user will start the jobs and given parameters is: AS_OF_DATE: "20180331" 因此,用户将启动作业,给定参数为: AS_OF_DATE: "20180331"

Then during the job I grep some text from test.txt file. 然后在工作期间,我从test.txt文件中提取了一些文本。

TEXT_FROM_FILE="This is my text, where i used ${AS_OF_DATE}"

And when I do the echo of $TEXT_FROM_FILE , variable $AS_OF_DATE is not changed with the date that user added. 当我执行$TEXT_FROM_FILE的回$TEXT_FROM_FILE ,变量$AS_OF_DATE不会随着用户添加的日期而改变。

My outcome is: 我的结果是:

"This is my text, where i used ${AS_OF_DATE}"

What it should be: 应该是什么:

"This is my text, where i used 20180331"

I assume that I am not declaring the variable inside the file correctly, so my question is hot to correctly specified the variable in file that will actually use the value that variable has instead of just outputting the text. 我假设我没有在文件内正确声明变量,所以我的问题很棘手,是要在文件中正确指定将实际使用变量具有的值而不是仅输出文本的变量。

Thank you in advance. 先感谢您。

It is nothing to do with the way you declare the variable in the file. 与在文件中声明变量的方式无关。 Having a variable name in a text string does not expand that name into its value unless you carry out an expansion operation on it. 在文本字符串中具有变量名不会将该名称扩展为其值,除非您对其执行扩展操作。 For example you could source the file if it contained executable bash commands, but just reading them as text would do nothing. 例如,如果文件包含可执行的bash命令,则可以将其作为source文件,但是仅将其读取为文本将无济于事。

There are a couple of solutions. 有两种解决方案。 One involves using eval , which I don't recommend since another command could be injected (like rm * ) and eval would execute it. 其中涉及使用eval ,我不建议这样做,因为可以注入另一个命令(例如rm * ),而eval可以执行它。 Besides, if I did suggest it I would (quite rightly) get down-voted like crazy. 此外,如果我建议的话,我(很正确)会像疯了似的被否决。

Safer would be to do a simple substitution: 比较安全的方法是做一个简单的替换:

AS_OF_DATE="20180331"

# I use single quotes to prevent expansion here
TEXT_FROM_FILE='This is my text, where i used ${AS_OF_DATE}'

final_text=${TEXT_FROM_FILE/'${AS_OF_DATE}'/$AS_OF_DATE}
echo "$final_text"

Gives: 得到:

This is my text, where i used 20180331

If you do this substitution and the variable name is not in the text then it just copies the existing string. 如果执行此替换并且变量名不在文本中,则它仅复制现有字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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