简体   繁体   English

Shell脚本传递带有变量的字符串,以便以后分配

[英]Shell scripting pass string with variable for later assignment

I am working on Mac OSX and using bash as my shell. 我正在使用Mac OSX并使用bash作为我的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. 谢谢你的帮助。

Sure, just use printf twice. 当然,只需使用printf两次。 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. 第一次,转义%s ,使其按原样进入字符串,第二次使用它作为格式字符串。

Str=$(printf '%d is %%s' 5)
New="something I know now"
printf "${Str}" "${New}"

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

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