Linux Bash 如何使用 for 循环获取输出并将其放回脚本中
Linux Bash how to grab output and put it back in the script using for loop
变量在bash中的值可以用echo $var
这样的命令轻松调用
user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ echo $a $b $c
1 2 a+b
user@linux:~$
我想要完成的是将 x
替换为 a,b,c
中的实际值
user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ for i in a b c; do echo "$i = x"; done
a = x
b = x
c = x
user@linux:~$
通过使用类似的for
循环,我希望我能得到这样的输出
a = 1
b = 2
c = a+b
使用间接:
$ for i in a b c; do echo "$i = ${!i}"; done
a = 1
b = 2
c = a+b
文档
间接在man bash
中解释:
If the first character of parameter is an exclamation point (!), and
parameter is not a nameref, it introduces a level of variable
indirection. Bash uses the value of the variable formed from the rest
of parameter as the name of the variable; this variable is then
expanded and that value is used in the rest of the substitution,
rather than the value of parameter itself. This is known as indirect
expansion. If parameter is a nameref, this expands to the name
of the variable referenced by parameter instead of performing the
complete indirect expansion. The exceptions
to this are the expansions of ${!prefix*} and ${!name[@]} described
below. The exclamation point must immediately follow the left
brace in order to introduce indirection.
变量在bash中的值可以用echo $var
这样的命令轻松调用
user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ echo $a $b $c
1 2 a+b
user@linux:~$
我想要完成的是将 x
替换为 a,b,c
user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ for i in a b c; do echo "$i = x"; done
a = x
b = x
c = x
user@linux:~$
通过使用类似的for
循环,我希望我能得到这样的输出
a = 1
b = 2
c = a+b
使用间接:
$ for i in a b c; do echo "$i = ${!i}"; done
a = 1
b = 2
c = a+b
文档
间接在man bash
中解释:
If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.