我不确定我是否正确说明了这一点.
这是我在bash脚本中的内容
ATEXT="this is a number ${i} inside a text string"
Run Code Online (Sandbox Code Playgroud)
然后我希望${i}在以下for循环中解决.
for i in {1..3}; do
echo "${ATEXT}"
done
Run Code Online (Sandbox Code Playgroud)
当然上面的方法不起作用,因为i在ATEXT读取变量时会解析.
但是,我不知道如何实现我想要的.这是获得输出:
this is a number 1 inside a text string
this is a number 2 inside a text string
this is a number 3 inside a text string
Run Code Online (Sandbox Code Playgroud)
对于参数化文本,请使用printf,而不是echo:
ATEXT="this is a number %d inside a text string"
for i in {1..3}; do
printf "$ATEXT\n" "$i"
done
Run Code Online (Sandbox Code Playgroud)
也可以看看:
可能我更喜欢@Chepner的答案 - 但作为一个很好的选择,你也可以做以下事情:
$ cat script
#!/usr/bin/env bash
_aText()
{
printf "this is a number %d inside a text string\n" $1
}
for i in {1..3}; do
_aText $i
done
$ ./script
this is a number 1 inside a text string
this is a number 2 inside a text string
this is a number 3 inside a text string
Run Code Online (Sandbox Code Playgroud)