Shell Jenkins job reading text from file with variables

Multi tool use
Shell Jenkins job reading text from file with variables
I am implementing Jenkins job in bash shell script. Jenkins jobs is using the variable AS_OF_DATE
which can be used as input for users.
AS_OF_DATE
I also have some files on zone with text that I grep during the execution of this jenkins job.
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
$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"
"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.
1 Answer
1
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.
source
bash
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. Besides, if I did suggest it I would (quite rightly) get down-voted like crazy.
eval
rm *
eval
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.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.