我必须在不同的行上打印 shell 脚本中解析的所有参数。我写了一个脚本
for i in 1 2 3 4 5
do
echo $i
done
但这打印
1
2
3
4
5
即使我将参数解析为“10 20 30 40 50”
和互联网上的一个代码
for i
do
echo $i
done
此代码正确打印参数。
有人能解释一下为什么该代码有效但我的代码无效吗?
另外,我如何使用一个变量($i)的值作为变量名来打印其他内容。喜欢
i=1
$($i)
应打印 $1 的值。
for i
相当于for i in "$@"
来自重击help for
:
for: for NAME [in WORDS ... ] ; do COMMANDS; done
Execute commands for each member in a list.
The 'for' loop executes a sequence of commands for each member in a
list of items. If 'in WORDS ...;' is not present, then 'in "$@"' is
assumed. For each element in WORDS, NAME is set to that element, and
the COMMANDS are executed.
If in WORDS ...;
不存在,那么in "$@"
假设
如果要从变量中获取变量,请使用间接扩展:
set -- arg1 arg2 arg3 foo
for i in 3 4 1 2
do
echo "${!i}"
done
# Output: arg3 foo arg2 arg1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)