1

I am working on Mac OSX and using bash as my shell. I was wondering if there was any way to create a string with some marker in it, that would later be evaluated. Such as:

Str=$(printf '%d is %s' "5" (#some string I don't know yet) )

Later...

some string I don't know yet="something I know now"
echo Str               #produces: 5 is something I know now

I know this in most cases could be remedy by moving the order of where I am placing the variables, but in this case I would like the order to be as is. Or is this not even possible? Thanks for your help.

1 Answer 1

4

Sure, just use printf twice. The fist time, escape the %s so that it goes into the string as-is, and the second time use it as the format string.

Str=$(printf '%d is %%s' 5)
New="something I know now"
printf "${Str}" "${New}"
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry I'm still new to coding in general, do you mean something like this? Str=$(printf '%d is \%s' "5" ) and then later Str=$(printf $Str "$some string I don't know yet"). Ah thank you, your edit has shown me.
Thanks again for your help, but is there also a way to pass an arithmetic operators say ** in the string and delay it's evaluation until you get the other variables in there? Say I had Str=5, and I know I wanted to raise it to the power, but I don't know what power yet.
@NoviceC You should post a new question which demonstrates an example of what you want to delay.
@NoviceC, yes, you can do that too. Use the same trick, but at the end use $((${Str} ${New})).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.