我必须将在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的值。
答案 0 :(得分:4)
for i
等效于for i in "$@"
来自Bash 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.
如果不存在
in WORDS ...;
,则假定为in "$@"
如果要从变量获取变量,请使用间接扩展:
set -- arg1 arg2 arg3 foo
for i in 3 4 1 2
do
echo "${!i}"
done
# Output: arg3 foo arg2 arg1